Search code examples
pythondjangomodelone-to-many

Adding one to many relationship in Django models


I have two models in my Django-REST application.

a ProjectRequest and a ContactRequest

I want to make it so, each Projectrequest contains a list of the refered Contactrequests.

class ProjectRequest(models.Model):
project_name = models.CharField(max_length=50)
company_name = models.CharField(max_length=50)
#make array of technologiestechnologies = models.ArrayField(base_field=) (blank=True)
project_description = models.CharField(max_length=200)
project_type = models.CharField(max_length=30)
budget_estimation = models.IntegerField(
    default=1000,
    validators=[
    MinValueValidator(1800),
    MaxValueValidator(5000000)
])
#time_estimation = models.DateTimeField(default=None, blank=True, null=True)


class ContactRequest(models.Model):
topic = models.CharField(max_length=30)
description = models.CharField(max_length=200)
time = models.CharField(max_length=15)
project_request = models.ForeignKey(ProjectRequest, 
on_delete=models.CASCADE)

so far I have established a relationship, with a foreign key, which works fine as of now. However I want to extends the functionality, so, that the ProjectRequest contains a list of all the projectrequest. I have tried with several different fields, without any luck, and the documentation I can only find fields for ManyToMany and OneToOne. How can this be achieved?


Solution

  • There are many ways to achive what you want. For that, lets add a reverse relation in model named contact_requests:

    project_request = models.ForeignKey(ProjectRequest, on_delete=models.CASCADE, related_name="contact_requests")
    

    Now you can use PrimaryKeyRelatedField to show Primary Keys of the ContactRequest attached to each ProjectRequest.

    class ProjectRequestSerializer(serializers.ModelSerializer):
        contact_requests = serializers.PrimaryKeyRelatedField(many=True, read_only=True)
    
        class Meta:
            model = ProjectRequest
            fields = ('contact_requests', 'company_name', ...)  # other fields 
    

    Or if you want all the values of each contact_requests, then you can use nested relationship like this:

    class ProjectRequestSerializer(serializers.ModelSerializer):
        contact_requests = ContactRequestSerializer(many=True, read_only=True)
    
        class Meta:
            model = ProjectRequest
            fields = ('contact_requests', 'company_name', ...) # and so on