如何在Django中自定义用户模型继承和序列化它们

a9wyjsp7  于 2023-10-21  发布在  Go
关注(0)|答案(1)|浏览(101)

尝试获取序列化程序UserSerializer上的字段ProDetails的值时出现AttributeError。序列化器字段可能命名不正确,并且与CustomUser示例上的任何属性或键都不匹配。原始例外文本为:CustomUser对象没有属性ProDetails

Models.py(示例网站)

class CustomUser(AbstractBaseUser, PermissionsMixin):
    username=None
    email = models.EmailField(unique=True)
    password = models.CharField(max_length=128, null=True)
    first_name = models.CharField(max_length=255, null=True, blank=True)
    last_name = models.CharField(max_length=255, null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    is_staff = models.BooleanField(default=False)
    is_superuser = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    is_shopCreated = models.BooleanField(default=False)
    last_login = models.DateTimeField(null=True, blank=True)
    last_logout = models.DateTimeField(null=True, blank=True)
    
    objects = UserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []
    
    def __str__(self):
        return self.email

    def has_module_perms(self, app_label):
        return True

    def has_perm(self, perm, obj=None):
        return True
class ProDetails(models.Model):
    user = models.OneToOneField(CustomUser, on_delete=models.CASCADE)
    mobile = models.CharField(max_length=14)
    address = models.CharField(max_length=500, null=True, blank=True)
    pincode = models.CharField(max_length=10, null=True, blank=True)
    profileimage = models.ImageField(
        upload_to='photos', max_length=100, null=True, blank=True)
    coverImg =  models.ImageField(
        upload_to='photos', max_length=100, null=True, blank=True)

Serializer.py(示例网站)

class ProDetailsSerializer(ModelSerializer):
    class Meta:
        model = ProDetails
        fields = ['id','pincode']

class UserSerializer(ModelSerializer):
    ProDetails = ProDetailsSerializer(required=True)
    class Meta:
        model = CustomUser
        fields = ['email', 'first_name', 'created_at', 'ProDetails']

View.py(示例网站)

class profiledata(mixins.RetrieveModelMixin,
                      mixins.ListModelMixin,
                      generics.GenericAPIView):
    serializer_class = UserSerializer
    lookup_field = 'id'
    authentication_classes = [
        JWTAuthentication, TokenAuthentication, SessionAuthentication, BasicAuthentication]
    permission_classes = [IsAuthenticated, ]

    def get_queryset(self):
        user = CustomUser.objects.all()
        return user

    def get(self, request, id=None):
       if id:
            return self.retrieve(request)
       else:
            item = self.list(request)
            return item
mwngjboj

mwngjboj1#

因此,要在使用SerializerModel时检索foreign key信息,必须将外键的related_name定义为序列化器字段。所以这里你没有在ProDetails model中为CustomerUser定义related_nane。所以默认情况下,Django将相关名称设置为prodetails_set。要解决这个问题,您必须将相关名称定义为UserSerializerProDetailsSerializer的字段名称。在此更改之后,序列化程序将如下所示

class UserSerializer(ModelSerializer):
    prodetails_set = ProDetailsSerializer(required=True)
    class Meta:
        model = CustomUser
        fields = ['email', 'first_name', 'created_at', 'prodetails_set']

相关问题