While working on a project, I learned how to associate a model with another model. This may be such a straightforward topic and I probably should’ve known this, but I’m just glad that I got to learn about this during personal project. I look forward to learning more from now on.
related_name for ForeignKey
This is the name that’s used to refer back to the object from the related object. It may be helpful to understand with an example. The following is a snippet from my Bookstand project.
Example
class Reading(models.Model):
...
reader = models.ForeignKey(
User, on_delete=models.CASCADE, related_name="readings"
)
In this example, User model will have access to the model Manager that returns all instances
of Reading model. Reading model’s manager returns querysets which can be filtered and manipulated.
After adding related_name for reader field, I updated UserSerializer as the following:
class UserSerializer(serializers.ModelSerializer):
readings = serializers.PrimaryKeyRelatedField(
many=True, queryset=Reading.objects.all()
)
class Meta:
model = User
fields = ["id", "username", "readings"]
PrimaryKeyRelatedField
The DRF document mentions that “PrimaryKeyRelatedField” may be used to represent the target
of the relationship using its primary key.
Arguments
queryset: “used for model instance lookups when validating the field input”many: “If applied to a to-many relationships, you should set this argument toTrue”allow_null: “If set toTrue, the field will accept values ofNoneor the empty string for nullable relationships”
Manager
A Manager is the interface through which database query operations are provided to Django models. At least one Manager exists for every model in a Django application.