簡體   English   中英

django-countries 如何添加序列化器字段

[英]django-countries how to add serializer field

我正在嘗試將 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

用戶 Model

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 的CountryField django_countries. serializer_fields django_countries. serializer_fields模塊,所以:

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 無效。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM