Django:如何避免在每次保存时重新分配ForeignKey?

时间:2013-01-05 16:35:13

标签: django django-database

我想保存A对象和B对象。 AB的外键。 B有一个OneToOneField到A。有没有办法可以在每次保存之间重新分配变量?或者有更好的方法来做到这一点?

# The models a and b were created earlier in code
# a.b = b  Was already set earlier in code
# b.a = a  Was already set earlier in code
with transaction.commit_on_success():
    a.save() # pk created for a
    b.a = a  # attach a.pk to b
    b.save() # pk created for b
    a.b = b  # attach b.pk to a
    a.save() # re-save a to database

1 个答案:

答案 0 :(得分:1)

“A有一个外键给B。B有一个OneToOneField到A.”我不认为这是建立你的人际关系的方式。您可以将B设置为A的ForeignKey,然后使用B.a_set.all()从B中访问A.

here开始,使用以下模型定义,Book是带Publisher的一对多(ForeignKey)和带有Author的多对多。 (~~~~只意味着与模型之间的关系无关的其他东西)

class Publisher(~~~~):
    ~~~~

class Author(~~~~):
    ~~~~

class Book(~~~~):
    publisher = models.ForeignKey(Publisher)
    authors = models.ManyToManyField(Author)

然后您可以从给定的书中访问发布者和作者,如下所示:

b = Book.objects.get(id=50)
publisher1 = b.publisher # publisher object for a given book
author_set = b.authors.all() # query set of authors for a given book

你可以做反向关系(在上面的模型中没有明确定义)。

p = Publisher.objects.get(name='Apress Publishing')
p.book_set.all() # query set of books for a given publisher
publisher1.book_set.all() # set of books for the publisher from above.
a = Author.objects.get(name="JK Rowling")
a.book_set.all() # query set of books for a given author

每次更新对象字段时,都需要调用save()将其保存在数据库中,但在执行此操作之前,您不需要重新分配ForeignKey或任何其他字段。如果那不适合你,可能是因为模特之间的时髦关系。我不是100%肯定,但我认为对象获得(新)主键的唯一时间是它第一次保存到数据库,然后这是它的第一个pk。