1

我正在尝试将 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)
    ...

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

4

1 回答 1

1

对于序列化程序,您导入模块CountryField的,所以:django_countries.serializer_fields

from django_countries.serializer_fields import CountryField

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

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

您因此继承:

class CustomRegisterSerializer(CountryFieldMixin, RegisterSerializer):
    # …

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

于 2022-01-25T20:04:37.610 回答