Home > Software design >  Django Rest framework: Relate 2 tables
Django Rest framework: Relate 2 tables

Time:09-30

I'm new at python and Django. I have a problem relate 2 tables

Participants Model

lass Participant(models.Model):

id = UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
first_name = CharField(max_length=255)
last_name = CharField(max_length=255)
current_employing_country = CharField(max_length=255)
current_payroll_country = CharField(max_length=255)
# locations = ManyToManyField(Location)

Location Model

class Location(models.Model):

participant_id = ForeignKey(Participant, on_delete=CASCADE,related_name="locations")
start_date = DateField()
end_date = DateField()
country = CharField(max_length=255)
region = CharField(max_length=255)
tax_policy = CharField(max_length=255, null=True)

Serializers

class ParticipantSerializer(serializers.ModelSerializer):
class Meta:
    model = Participant
    fields = "__all__"

class LoactionSerializer(serializers.ModelSerializer):
# participant_id = serializers.PrimaryKeyRelatedField(queryset=Participant.objects.all())

class Meta:
    model = Location
    tax_policy = serializers.CharField(allow_blank=True, allow_null=True)
    fields = "__all__"

Trying to get all participants with property locations that contain array of all the locations that relate to the participant id like Participant.objects.all().prefetch_related("locations")

EXAMPLE-

[
{
    "id": "a9a6c412-91c2-414a-97dc-8f8a4c6bdfcd",
    "first_name": "test",
    "last_name": "test",
    "nationality": "test",
    "current_employing_country": "israel",
    "current_payroll_country": "dsadsa",
    "locations": [ {
        "id": 1,
        "start_date": "2021-10-10",
        "end_date": "2021-11-11",
        "country": "isreal",
        "region": "iseali",
        "tax_policy": "N/A",
        "participant_id": "a9a6c412-91c2-414a-97dc-8f8a4c6bdfcd"
       },
       {
        "id": 2,
        "start_date": "2021-10-10",
        "end_date": "2021-11-11",
        "country": "adsdsa",
        "region": "iseali",
        "tax_policy": "N/A",
        "participant_id": "a9a6c412-91c2-414a-97dc-8f8a4c6bdfcd"
    }]
}

]

CodePudding user response:

It just like below.

class LocationSerializer(serializers.ModelSerializer):
    class Meta:
        model = Location
        fields = "__all__"


class ParticipantSerializer(serializers.ModelSerializer):
    locations = LocationSerializer(many=True)

    class Meta:
        model = Participant
        fields = (
            "id",
            "first_name",
            "last_name",

            "locations",
        )

  • Related