Shift N' Tab Shift N' Tab - 1 year ago 104
Python Question

What is the Correct Django Model Relationship

Im a beginner in django and its modeling structure. And i would like to seek answer from anyone.

I have a model


Each herd has a multiple animals and an animal belongs to a herd. So i design this many-to-one model relationship as an example. Am i in a wrong way or should i continue this practice? Because i am confuse with the djangorestframework serializer relations of
model relationship. Please help.

class Animal(models.Model):
name = models.CharField(max_length=25)
date_of_birth = models.DateField()
birth_weight = models.IntegerField()
sex = models.CharField(max_length=7)
sibling_order = models.IntegerField()

class Herd(models.Model):
animal = models.ForeignKeyField(Animal, related_name="animals", on_delete=models.CASCADE)
name = models.CharField(max_length=25)
description = models.TextField(max_length=250, null=True)

Answer Source

This is the wrong way round. You have a herd consisting of a single animal, but an animal belonging to many herds. You need to have the ForeignKey in Animal, pointing to Herd.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download