0

I want to save the A object and B object. A has a foreignkey to B. B has a OneToOneField to A. Is there a way I can get around having to reassign the variables between each save? or perhaps there's a better way to do it?

# 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
4

1 回答 1

1

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

这里解释一下,使用以下模型定义,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。

于 2013-01-05T17:04:59.143 回答