尝试获取序列化程序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
1条答案
按热度按时间mwngjboj1#
因此,要在使用
SerializerModel
时检索foreign key
信息,必须将外键的related_name
定义为序列化器字段。所以这里你没有在ProDetails model
中为CustomerUser
定义related_nane
。所以默认情况下,Django将相关名称设置为prodetails_set
。要解决这个问题,您必须将相关名称定义为UserSerializer
中ProDetailsSerializer
的字段名称。在此更改之后,序列化程序将如下所示