两个带有外键引用的表相互引用
我有两个应用程序 - 一个用于狗,一个用于窝 - 理想情况下,我会将外键相互返回,如下所示:
在 dogs.py 中:
from litters.py import Litter
class Dog(models.Model):
name = models.CharField(max_length=55)
Litter = models.ForeignKey(Litter, blank=True)
在 litters.py
from dogs.py import Dog
class Litter(models.Model):
name = models.CharField(max_length=55)
sire = models.ForeignKey(Dog, related_name='dog_sire_set')
dam = models.ForeignKey(Dog, related_name='dog_dam_set'
创建新窝时,我想要窝的母亲和父亲(妈妈和爸爸)来自我的狗桌,因此两个FK是母亲和父亲。因此,在我创建一窝幼崽之前,我必须至少拥有两条狗条目。
后来,当描述新的狗条目时,我想知道狗的窝(如果知道),并且该窝应该来自我的窝表。不应该要求狗生一窝,但如果该字段不为空,那么我想知道它。
上面的代码不起作用,但它演示了我想要实现的目标。我将不胜感激任何有关如何解决此问题的提示。谢谢。
I have two apps - one for dogs and one for litters - where ideally I would have foreign keys back to each other, something like this:
In dogs.py:
from litters.py import Litter
class Dog(models.Model):
name = models.CharField(max_length=55)
Litter = models.ForeignKey(Litter, blank=True)
In litters.py
from dogs.py import Dog
class Litter(models.Model):
name = models.CharField(max_length=55)
sire = models.ForeignKey(Dog, related_name='dog_sire_set')
dam = models.ForeignKey(Dog, related_name='dog_dam_set'
When creating a new litter, I want the litter's dam and sire (mom and dad) to come from my table of dogs, hence the two FK's to dam and sire. So before I can create a litter, I must have at least two dog entries.
Later, when describing new dog entries, I want to know the dog's litter if known, and that litter should be from my litter table. It should not be required that a dog have a litter, but if that field is not null, then I'd like to know it.
The code above will not work but it demonstrates what I want to achieve. I'd be appreciative of any tips on how to solve this. Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
blank=True
告诉管理员该字段不需要由用户输入。但你仍然要告诉数据库同样的事情,你需要添加null =正确
。如果您遇到循环导入问题,请将 模型名称作为字符串< /a>.如果没有垃圾,田地里就没有垃圾。
blank=True
tells admin that this field is not required to be entered by user. But you still to tell DB same thing, you need to addnull=True
. And if you have circular import problem, put model name as a string.If there's no litter, the field will have None.
使用惰性关系。
在 dogs.py 中:
在 litters.py 中:
示例:
use lazy relationships.
in dogs.py:
in litters.py:
example: