获取特定模型的request.user和特定用户的记录该如何操作?

huangapple go评论103阅读模式
英文:

How can I get the records (of a specific model) of both request.user and a specific user?

问题

I am not very professional in django rest...

I wrote a blog with django rest framework and There is no problem when I want to get all the records related to the Article model or get a specific article, for example

But what I want to do is to send a user id (or a username) to the view when I click on the user's name, and as a result, display all the records of the Article model related to the request.user and all the records of the Article model related to the user whose name was clicked.

In fact, I want to click on the name of each user, in addition to getting the Articles of that user, the Articles related to the request.user will also be taken.

This is what I have done so far...

  1. #models.py
  2. class Article(models.Model):
  3. title = models.CharField(max_length=255)
  4. slug = models.SlugField
  5. author = models.ForeignKey(User, on_delete=models.CASCADE)
  6. content = models.TextField(null=True)
  7. publish = models.DateTimeField(default=timezone.now)
  8. created = models.DateTimeField(auto_now_add=True)
  9. updated = models.DateTimeField(auto_now=True)
  10. status = models.BooleanField(default=False)
  11. def __str__(self):
  12. return self.title
  13. class Profile(models.Model):
  14. user = models.OneToOneField(User, on_delete=models.CASCADE)
  15. name = models.CharField(max_length=100)
  16. pic = models.ImageField(upload_to="img", blank=True, null=True)
  17. def __str__(self):
  18. return self.user.username
  19. #views.py
  20. class ArticleCreate(CreateAPIView):
  21. queryset = Article.objects.all()
  22. serializer_class = ArticleSerializer
  23. class ArticleList(ListAPIView):
  24. queryset = Article.objects.all()
  25. serializer_class = ArticleSerializer
  26. class ArticleDetail(RetrieveUpdateDestroyAPIView):
  27. queryset = Article.objects.all()
  28. serializer_class = ArticleSerializer
  29. class UserDetail(RetrieveUpdateDestroyAPIView):
  30. queryset = get_user_model().objects.all()
  31. serializer_class = UserSerializer
  32. class UserProfile(RetrieveUpdateDestroyAPIView):
  33. queryset = Profile.objects.all()
  34. serializer_class = ProfileSerializer
  35. #serializers.py
  36. class UserSerializer(serializers.ModelSerializer):
  37. class Meta:
  38. model = get_user_model()
  39. fields = "__all__"
  40. class ProfileSerializer(serializers.ModelSerializer):
  41. class Meta:
  42. model = Profile
  43. fields = "__all__"
  44. class ArticleSerializer(serializers.ModelSerializer):
  45. class Meta:
  46. model = Article
  47. exclude = ['updated', 'created']

(Note: I have removed HTML entities like " and replaced them with actual characters for better readability.)

英文:

I am not very professional in django rest...

I wrote a blog with django rest framework and There is no problem when I want to get all the records related to the Article model or get a specific article, for example

But what I want to do is to send an user id(or an user name) to the view when I click on the user's name.

and as a result display all the records of the Article model related to the request.user and all the records of the Article model related to the user whose name was clicked.

In fact, I want to click on the name of each user, in addition to getting the Articles of that user, the Articles related to the request.user will also be taken

This is what I have done so far...

  1. #models.py
  2. class Article(models.Model):
  3. title = models.CharField(max_length=255)
  4. slug = models.SlugField
  5. author = models.ForeignKey(User , on_delete = models.CASCADE)
  6. content = models.TextField(null = True)
  7. publish = models.DateTimeField(default = timezone.now)
  8. created = models.DateTimeField(auto_now_add = True)
  9. updated = models.DateTimeField(auto_now = True)
  10. status = models.BooleanField(default = False)
  11. def __str__(self):
  12. return self.title
  13. class Profile(models.Model):
  14. user = models.OneToOneField(User, on_delete=models.CASCADE)
  15. name = models.CharField(max_length=100)
  16. pic = models.ImageField(upload_to="img", blank=True, null=True)
  17. def __str__(self):
  18. return self.user.username
  19. #views.py
  20. class ArticleCreate(CreateAPIView):
  21. queryset = Article.objects.all()
  22. serializer_class = ArticleSerializer
  23. class ArticleList(ListAPIView):
  24. queryset = Article.objects.all()
  25. serializer_class = ArticleSerializer
  26. class ArticleDetail(RetrieveUpdateDestroyAPIView):
  27. queryset = Article.objects.all()
  28. serializer_class = ArticleSerializer
  29. class UserDetail(RetrieveUpdateDestroyAPIView):
  30. queryset = get_user_model().objects.all()
  31. serializer_class = UserSerializer
  32. class UserProfile(RetrieveUpdateDestroyAPIView):
  33. queryset = Profile.objects.all()
  34. serializer_class = ProfileSerializer
  35. #serializers.py
  36. class UserSerializer(serializers.ModelSerializer):
  37. class Meta:
  38. model = get_user_model()
  39. fields = "__all__"
  40. class ProfileSerializer(serializers.ModelSerializer):
  41. class Meta:
  42. model = Profile
  43. fields = "__all__"
  44. class ArticleSerializer(serializers.ModelSerializer):
  45. class Meta:
  46. model = Article
  47. exclude = ['updated' , 'created']

答案1

得分: 1

你应该直接在get_queryset()方法中使用Q对象进行多处修改,如下所示:

  1. class ArticleList(ListAPIView):
  2. queryset = Article.objects.all()
  3. serializer_class = ArticleSerializer
  4. def get_queryset(self):
  5. user_id = self.kwargs.get('user_id')
  6. if user_id:
  7. articles = Article.objects.filter(Q(author_id=user_id) | Q(author=self.request.user))
  8. return articles
  9. return self.queryset

你还需要修改你的urls.py文件,以在URL中包含user_id参数,如下所示:

  1. from django.urls import path
  2. from .views import ArticleList
  3. urlpatterns = [
  4. path('articles/<int:user_id>/', ArticleList.as_view(), name='article_list'),
  5. # ... 其他路由。
  6. ]
英文:

You should directly make several modifications in get_queryset() method by using Q objects so:

  1. class ArticleList(ListAPIView):
  2. queryset = Article.objects.all()
  3. serializer_class = ArticleSerializer
  4. def get_queryset(self):
  5. user_id = self.kwargs.get(&#39;user_id&#39;)
  6. if user_id:
  7. articles = Article.objects.filter(Q(author_id=user_id) | Q(author=self.request.user))
  8. return articles
  9. return self.queryset

You'll also need to modify your urls.py file to include the user_id parameter in the URL so:

  1. from django.urls import path
  2. from .views import ArticleList
  3. urlpatterns = [
  4. path(&#39;articles/&lt;int:user_id&gt;/&#39;, ArticleList.as_view(), name=&#39;article_list&#39;),
  5. # ... Other routes.
  6. ]

答案2

得分: 1

class ArticleList(ListAPIView):
queryset = Article.objects.all()
serializer_class = ArticleSerializer

  1. def get_queryset(self):
  2. username = self.request.query_params.get('username')
  3. if username:
  4. return User.objects.filter(username=username).article_set.all()
  5. user = self.request.user
  6. return Article.objects.filter(author=user)
英文:

example URL: http://example.com/api/purchases?username=denvercoder9

  1. class ArticleList(ListAPIView):
  2. queryset = Article.objects.all()
  3. serializer_class = ArticleSerializer
  4. def get_queryset(self):
  5. username = self.request.query_params.get(&#39;username&#39;)
  6. if username:
  7. return User.objects.filter(username=username).article_set.all()
  8. user = self.request.user
  9. return Article.objects.filter(author=user)

huangapple
  • 本文由 发表于 2023年2月8日 13:01:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/75381544.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定