python - 序列化程序和json响应的奇怪错误
问题描述
我有一个配置文件模型,我使用“ all ”序列化和设置字段。问题是,当我运行它时,我收到以下错误:
AttributeError at /api/accounts/profile/
'User' object has no attribute 'following'
我尝试手动设置字段并得到相同的错误,但是当我从字段中删除以下内容时,它会正常运行并且我得到正常的 JSON 响应,但是所有字段都显示为 null 而不是我在管理面板中设置的数据。
{
"pk": 2,
"date_of_birth": null,
"bio": null,
"profile_photo": null,
"sex": null,
"type_of_body": null,
"feet": null,
"inches": null,
"lives_in": null
}
下面是应用程序其余部分的代码
模型.py
class Profile(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
following = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='followers', blank=True)
date_of_birth = models.DateField(blank=True, null=True, verbose_name="DOB")
bio = models.TextField(max_length=500, null=True, blank=True)
profile_photo = models.CharField(blank=True, null=True, max_length=300)
sex = models.CharField(max_length=1, choices=SEX, blank=True, null=True)
type_of_body = models.CharField(max_length=8, choices=BODYTYPE, blank=True, null=True)
feet = models.PositiveIntegerField(blank=True, null=True)
inches = models.PositiveIntegerField(blank=True, null=True)
lives_in = models.CharField(max_length=50, blank=True, null=True)
updated_on = models.DateTimeField(auto_now_add=True)
序列化程序.py
class ProfileSerializer(serializers.ModelSerializer):
class Meta:
model = Profile
fields = '__all__'
read_only_fields = ('pk', 'user', 'following', 'height')
视图.py
class CurrentUserProfileAPIView(APIView):
permission_classes = [IsAuthenticated]
def get(self, request):
serializer = ProfileSerializer(request.user)
return Response(serializer.data)
网址.py
urlpatterns = [
url(r'^profile/$', CurrentUserProfileAPIView.as_view(), name="my_profile")
]
解决方案
request.user
settings.AUTH_USER_MODEL
返回(或AnonymousUser
任何未经身份验证的用户)的实例- 请求用户,但您正在尝试使用模型的序列化程序Profile
(ProfileSerializer
)对其进行序列化。
由于用户没有提到的Profile
模型属性,所有字段都被序列化为null
. 而pk
是user.pk
,它存在于任何 Django 模型实例上(总是指使用的公钥)。
推荐阅读
- c# - 异常没有给出它发生的文件或行
- javascript - FullCalendar 行 Javascript
- c# - 我应该使用什么模式来防止耗时过长的异步调用溢出
- java - Android:访问内部 AsyncTask 类的变量,但在片段的 onCreateView 中将其设置为 null
- git - git rebase/checkout 保留最新修改的文件
- sql - 在查询中直接跳过身份
- r - 在ggplot2中绘制具有因子水平的垂直线
- angular - 在 fileSaver.saveAs() 完成后启用标志或其他东西
- javascript - 在 OOP Javascript 中锁定特权方法
- r - 基本数据框程序