【问题标题】:Trying to relate tables in Django试图在 Django 中关联表
【发布时间】:2021-11-24 06:06:44
【问题描述】:

尝试 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": ["无效数据。需要字典,但得到了字符串。"]}}

当我设法以 dict 发送时,但我有另一个错误,要求所有国家/地区字段,所以我从数据库中获取特定国家/地区,当我发送它时,我收到 json 错误

【问题讨论】:

  • 外键字段名不用id结束。 Django 为你做这件事。 country = ForeignKey() 可以。

标签: django django-models django-rest-framework django-views django-serializer


【解决方案1】:

这个

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

【讨论】:

  • 没有改变任何东西
【解决方案2】:

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

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

【讨论】:

  • 我可以在删除此行时创建一个新位置,但是我没有看到相关国家/地区只设置了 id
  • 有一些选项可以解决这个问题。您可以覆盖 create 函数,也可以使用不同的序列化程序进行读取和写入。
【解决方案3】:

您可以在this answer了解更多详情

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 中有错字。

【讨论】:

  • 你就是男人
猜你喜欢
  • 2022-01-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-21
  • 2014-08-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多