使Django Rest Api用户特定(get_queryset)

时间:2019-06-02 19:28:50

标签: django django-models django-rest-framework django-views django-urls

我想制作一个特定于用户的Django rest api,以便在网址末尾使用/ username。

型号:

class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
age = models.IntegerField()
description = models.CharField(max_length=300)

class Meta:
    verbose_name_plural = 'User Profiles'

def __str__(self):
    return self.user.username

@receiver(post_save, sender=User)
def create_user_data(sender, update_fields, created, instance, **kwargs):
if created:
    user  = instance
    profile = UserProfile.objects.create(user=user, age=18, description='No Description')

class Notes(models.Model):
note = models.CharField(max_length=1000)
parent_user = models.OneToOneField(UserProfile, blank=True, on_delete=models.CASCADE)

class Meta:
    verbose_name_plural = 'Notes'

def __str__(self):
    return self.note

序列化器:

class NoteSerializer(serializers.ModelSerializer):
class Meta:
    model = Notes
    fields = ('id', 'note', 'parent_user')

网址:

router = routers.DefaultRouter()
router.register('notes', views.UserNoteView)

urlpatterns = [
    path('', include(router.urls)),
]

观看次数:

class NoteView(viewsets.ModelViewSet):
http_method_names = ['get', 'post', 'put', 'delete', 'patch']
queryset = Notes.objects.all()
serializer_class = NoteSerializer

class UserNoteView(NoteView):
def get_queryset(self):
    return self.request.parent_user.Notes.all()

我的问题是我无法执行/ William这样的用户名和用户个人资料。知道这一点的人一定能够提供帮助!

2 个答案:

答案 0 :(得分:2)

您以错误的方式过滤了 QuerySet 。尝试以下代码段,

class UserNoteView(NoteView):
    def get_queryset(self):
        return Notes.objects.filter(parent_user__user=self.request.user)

因此,您无需向API端点添加任何用户名。 DRF将获取登录的用户信息(如果您指定了身份验证类),然后过滤出与该用户相对应的 Notes

答案 1 :(得分:0)

您的笔记model不正确。将OneToOneField更改为ForeignKey。您可以如下更改

class Notes(models.Model):
    note = models.CharField(max_length=1000)
    parent_user = models.ForeignKey(
        UserProfile, blank=True, on_delete=models.CASCADE, related_name="notes")

    def __str__(self):
        return "{note}".format(note=self.note)

现在,如下更改您的viewset

class UserNoteView(NoteView):

    def get_queryset(self):
        return self.request.user.userprofile.notes.all()
        # or
        return Notes.objects.filter(parent_user__user=self.request.user)