如何序列化来自django国家的CountryField



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

我找到的所有答案都只是说用文件上说的,但这对我没有帮助,也许我只是做得不对。

这就是django国家的文件所说的:

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)
...

除此之外,我尝试了不同的方法,但都没有成功。

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

from django_countries.serializer_fields importCountryField
class CustomRegisterSerializer(RegisterSerializer):
# …
country =CountryField()
# …

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

您因此继承:

class CustomRegisterSerializer(CountryFieldMixin, RegisterSerializer):
# …

在这种情况下,您应该而不是手动指定country序列化程序字段,因为这将使mixin无效。

最新更新