Django休息框架:使用OneToOneField无法获取

2024-07-04 07:50:27 发布

您现在位置:Python中文网/ 问答频道 /正文

当我使用Django REST框架时,使用OneToOneField和RetrieveUpdateDestroyAPIView无法通过pk获得; 我的代码如下:

你知道吗型号.py你知道吗

class UserAccount(models.Model):
    username = models.CharField(null=False, max_length=45) 
    password = models.CharField(null=False, max_length=16) 

class UserContactInfo(models.Model):
    userAccount = models.OneToOneField(UserAccount, primary_key=True)
    phone_number = models.CharField(null=True, blank=True)
    email = models.CharField(null=True, blank=True, max_length=45)

你知道吗序列化程序.py你知道吗

class UserAccountSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserAccount
        fields = ('id', 'username', 'password')


class UserContactInfoSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserContactInfo
        fields = ('userAccount', 'phone_number', 'email')

你知道吗视图.py你知道吗

class UserContactInfoDetail(generics.RetrieveUpdateDestroyAPIView):
    queryset = UserAccount.objects.all()
    serializer_class = UserContactInfoSerializer

你知道吗网址.py你知道吗

urlpatterns = [
    ...
    url(r'^ContactInfo/(?P<pk>[0-9]+)/$',    views.UserContactInfoDetail.as_view()),
    ]

好的,当我尝试获取UserContactInfo数据时:

GET http://127.0.0.1:8000/ContactInfo/1/

然后出错:

AttributeError at /ContactInfo/1/
'UserAccount' object has no attribute 'userAccount_id'

Request Method: GET
Request URL: http://127.0.0.1:8000/ContactInfo/1/
.....

谁能帮我修好它。谢谢!你知道吗


Tags: pytruemodelsnulllengthmaxclasscharfield

热门问题