尝试关联 Django 中的表

Trying to relate tables in Django

正在尝试POST请求并创建新位置。现在提交的 country_id 暗示了很多麻烦。 这些是 类

class Country(models.Model):
id = UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
country_name = CharField(max_length=255)
federal_rate = FloatField()
social_security = FloatField()
comment = CharField(max_length=255)

class Location(models.Model):
participant_id = ForeignKey('Participant', on_delete=CASCADE, related_name="locations")
country_id = ForeignKey('Country', on_delete=CASCADE, related_name="country")
start_date = DateField()
end_date = DateField()
region = CharField(max_length=255)
tax_policy = CharField(max_length=255, null=True)

序列化器

class CountrySerializer(serializers.ModelSerializer):

class Meta:
    model = Country
    fields = "__all__"

class LoactionSerializer(serializers.ModelSerializer):
country_id = CountrySerializer(many=False)

class Meta:
    model = Location
    fields = "__all__"

现在我设法加入表格的唯一原因是在排序器中添加 country_id 行,当我尝试创建新位置时,出现错误 这是我尝试添加新位置的方式

{
"start_date": "2021-10-10",
"end_date": "2021-11-18",
"region": "markian-land",
"tax_policy": "N/A",
"participant_id": "c5c1a00c-4263-418a-9f3a-3ce40a1ea334",
"country_id": "9067e71f-c6b9-4ecc-ad6b-461843063aee"
}

错误 - {"country_id": {"non_field_errors": ["无效数据。需要一个字典,但得到了 str。"]}}

当我设法作为字典发送时,但我有另一个错误要求所有国家字段,所以我从数据库中获取特定国家,当我发送它时我得到 json 错误

这个

country_id = ForeignKey(Country, on_delete=CASCADE, related_name="country")

您在 LocationSerializer 和 CountrySerializer 中将 country_id 定义为 CountrySerializer,fields = "__all__" 意味着您需要传递所有国家/地区对象字段才能使其工作。

尝试删除 LocationSerializer 中的 country_id = CountrySerializer(many=False),然后重试。

您可以在

中了解更多详细信息

Django Rest Framework不提供此功能,您需要先创建一个序列化器字段。

from rest_framework import serializers


class RelatedFieldAlternative(serializers.PrimaryKeyRelatedField):
    def __init__(self, **kwargs):
        self.serializer = kwargs.pop('serializer', None)
        if self.serializer is not None and not issubclass(self.serializer, serializers.Serializer):
            raise TypeError('"serializer" is not a valid serializer class')

        super().__init__(**kwargs)

    def use_pk_only_optimization(self):
        return False if self.serializer else True

    def to_representation(self, instance):
        if self.serializer:
            return self.serializer(instance, context=self.context).data
        return super().to_representation(instance)

然后在 Location 序列化器中使用这个新的序列化器字段作为,

class LoactionSerializer(serializers.ModelSerializer):
    country_id = RelatedFieldAlternative(queryset = Country.objects.all(),
                     serializer=CountrySerializer)

    class Meta:
        model = Location
        fields = "__all__"

请注意:您在 LoactionSerializer 中有错字。