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.
blank=Truetells 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.