English 中文(简体)
Django的保存(save())函数中的外键访问
原标题:
  • 时间:2008-11-20 22:10:21
  •  标签:

Here s my code:

class Publisher(models.Model):
    name = models.CharField(
            max_length = 200,
            unique = True,
    )

    url = models.URLField()

    def __unicode__(self):
        return self.name

    def save(self):
        pass

class Item(models.Model):
    publisher = models.ForeignKey(Publisher)

    name = models.CharField(
            max_length = 200,
    )

    code = models.CharField(
            max_length = 10,
    )

    def __unicode__(self):
        return self.name

I want to be able to access each Item from the Publisher save function. How can I do this?

For instance, I d like to append text to the code field of each Item associated with this Publisher on the save of Publisher.

edit: When I try to implement the first solution, I get the error " Publisher object has no attribute item_set ". Apparently I can t access it that way. Any other clues?

edit 2: I discovered that the problem occurring is that when I create a new Publisher object, I add Items inline. Therefor, when trying to save a Publisher and access the Items, they don t exist.

有没有绕过这个的方法?!

最佳回答

你应该能够做以下类似的事情:

def save(self, **kwargs):
    super(Publisher, self).save(**kwargs)

    for item in self.item_set.all():
        item.code = "%s - whatever" % item.code

我真的不喜欢你在这里做的事情,这不是一个好的将项目发布者联系起来的方式。你最终想要的是什么?

问题回答

暂无回答




相关问题
热门标签