【问题标题】:django-countries how to add serializer fielddjango-countries 如何添加序列化器字段
【发布时间】:2022-01-25 14:47:15
【问题描述】:

我正在尝试将 CountryField 添加到 Register 进程的序列化程序中(使用 dj-rest-auth),但找不到正确的实现方法。

我找到的所有答案都只是说要使用文档所说的内容,但这对我没有帮助,也许我只是做得不对。

django-countries 的文档是这样说的:

from django_countries.serializers import CountryFieldMixin

class CountrySerializer(CountryFieldMixin, serializers.ModelSerializer):

class Meta:
    model = models.Person
    fields = ('name', 'email', 'country')

我需要在这里添加字段:

class CustomRegisterSerializer(RegisterSerializer, CountryFieldMixin):

    birth_date = serializers.DateField()
    country = CountryField()
    gender = serializers.ChoiceField(choices=GENDER)

    # class Meta:
    #     model = User
    #     fields = ('country')

    # Define transaction.atomic to rollback the save operation in case of error
    @transaction.atomic
    def save(self, request):
        user = super().save(request)
        user.birth_date = self.data.get('birth_date')
        user.country = self.data.get('country')
        user.gender = self.data.get('gender')
        user.save()
        return user

用户模型

class User(AbstractUser):
    """
    Default custom user model
    """

    name = models.CharField(max_length=30)

    birth_date = models.DateField(null=True, blank=True)
    country = CountryField(null=True, blank=True, blank_label='Select country')
    gender = models.CharField(choices=GENDER, max_length=6, null=True, blank=True)
    ...

除此之外我尝试了不同的方法,但没有任何效果。

【问题讨论】:

  • 从哪里导入CountryField?您能否分享您的User 模型的相关部分(尤其是您如何定义country 字段)。
  • 已经添加了用户模型的重要部分,我从from django_countries.fields import CountryField导入CountryField

标签: python django django-rest-framework django-countries dj-rest-auth


【解决方案1】:

对于序列化器,你导入django_countries.<b>serializer_fields</b>模块的CountryField,所以:

from django_countries.serializer_fields import CountryField

class CustomRegisterSerializer(RegisterSerializer):
    # …
    country = CountryField()
    # …

如果您想使用Mixin(它将使用这样的CountryField 序列化器字段),您应该在RegisterSerializer 之前指定CountryFieldMixin,否则它不会覆盖.build_standard_field(…) 方法。

您因此继承:

class CustomRegisterSerializer(CountryFieldMixin, RegisterSerializer):
    # …

在这种情况下,您应该手动指定 country 序列化器字段,因为这会使 mixin 无效。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-20
    • 2016-03-11
    • 2016-08-10
    • 2017-04-13
    • 1970-01-01
    • 2016-10-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多