Django Rest framework: Относительно 2 таблиц

Я новичок в python и Django. У меня проблема связать 2 таблицы

Модель участников

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)

Модель местоположения

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__"

Попытка получить всех участников со свойством locations, которое содержит массив всех местоположений, относящихся к идентификатору участника, как 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"
    }]
}

]

Вот так, как показано ниже.

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",
        )

Вернуться на верх