two tables with foreign key references back to each other
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 lit开发者_如何学Cter'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.
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 add null=True
. And if you have circular import problem, put model name as a string.
Litter = models.ForeignKey('Litter', blank=True, null=True)
If there's no litter, the field will have None.
use lazy relationships.
in dogs.py:
class Dog(models.Model):
name = models.CharField(max_length=55)
litter = models.ForeignKey('litters.Litter', blank=True, null=True)
in litters.py:
class Litter(models.Model):
name = models.CharField(max_length=55)
sire = models.ForeignKey('dogs.Dog', related_name='litters_sired')
dam = models.ForeignKey('dogs.Dog', related_name='litters_damed')
example:
dog1 = Dog(name='Bob')
dog1.save()
dog2 = Dog(name='Jane')
dog2.save()
litter1 = Litter(name='BobJane', sire=dog1, dam=dog2)
litter1.save()
dog3 = Dog(name='Sonny', litter=litter1)
dog3.save()
dog1.litters_sired
[<BobJane>]
dog1.litters_damed
[]
dog1.litter
None
dog2.litters_sired
[]
dog2.litters_damed
[<BobJane>]
dog2.litter
None
dog3.litters_sired
[]
dog2.litters_damed
[]
dog2.litter
BobJane
精彩评论