[Django]-Two tables with foreign key references back to each other

9👍

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.

0👍

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
👤dting

Leave a comment