Django REST框架:使用OneToOneField无法获取

时间:2017-01-22 16:45:12

标签: python django django-rest-framework

当我使用Django REST框架时,使用Use OneToOneField和RetrieveUpdateDestroyAPIView不能通过pk获取; 我的代码如下:

models.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)

serializers.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')

views.py

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

urls.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/
.....

谁能帮我解决问题。谢谢!

1 个答案:

答案 0 :(得分:0)

我认为你在查询集中有拼写错误:
queryset = UserAccount.objects.all()代替UserContactInfo.objects.all()