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

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

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

#models.py

class Article(models.Model):
    title = models.CharField(max_length=255)
    slug = models.SlugField
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    content = models.TextField(null=True)
    publish = models.DateTimeField(default=timezone.now)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    status = models.BooleanField(default=False)

    def __str__(self):
        return self.title

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    name = models.CharField(max_length=100)
    pic = models.ImageField(upload_to="img", blank=True, null=True)

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

#views.py

class ArticleCreate(CreateAPIView):
    queryset = Article.objects.all()
    serializer_class = ArticleSerializer

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

class ArticleDetail(RetrieveUpdateDestroyAPIView):
    queryset = Article.objects.all()
    serializer_class = ArticleSerializer

class UserDetail(RetrieveUpdateDestroyAPIView):
    queryset = get_user_model().objects.all()
    serializer_class = UserSerializer

class UserProfile(RetrieveUpdateDestroyAPIView):
    queryset = Profile.objects.all()
    serializer_class = ProfileSerializer

#serializers.py

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = get_user_model()
        fields = "__all__"

class ProfileSerializer(serializers.ModelSerializer):
    class Meta:
        model = Profile
        fields = "__all__"

class ArticleSerializer(serializers.ModelSerializer):
    class Meta:
        model = Article
        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...

#models.py
class Article(models.Model):
title = models.CharField(max_length=255)
slug = models.SlugField
author = models.ForeignKey(User , on_delete = models.CASCADE)
content = models.TextField(null = True)
publish = models.DateTimeField(default = timezone.now)
created = models.DateTimeField(auto_now_add = True)
updated = models.DateTimeField(auto_now = True)
status = models.BooleanField(default = False)
def __str__(self):
return self.title
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
name = models.CharField(max_length=100)
pic = models.ImageField(upload_to="img", blank=True, null=True)
def __str__(self):
return self.user.username
#views.py
class ArticleCreate(CreateAPIView):
queryset = Article.objects.all()
serializer_class = ArticleSerializer
class ArticleList(ListAPIView):
queryset = Article.objects.all()
serializer_class = ArticleSerializer
class ArticleDetail(RetrieveUpdateDestroyAPIView):
queryset = Article.objects.all()
serializer_class = ArticleSerializer
class UserDetail(RetrieveUpdateDestroyAPIView):
queryset = get_user_model().objects.all()
serializer_class = UserSerializer
class UserProfile(RetrieveUpdateDestroyAPIView):
queryset = Profile.objects.all()
serializer_class = ProfileSerializer
#serializers.py
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = get_user_model()
fields = "__all__"
class ProfileSerializer(serializers.ModelSerializer):
class Meta:
model = Profile
fields = "__all__"
class ArticleSerializer(serializers.ModelSerializer):
class Meta:
model = Article
exclude = ['updated' , 'created']

答案1

得分: 1

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

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

    def get_queryset(self):
        user_id = self.kwargs.get('user_id')
        if user_id:
            articles = Article.objects.filter(Q(author_id=user_id) | Q(author=self.request.user))
            return articles
        return self.queryset

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

from django.urls import path
from .views import ArticleList

urlpatterns = [
    path('articles/<int:user_id>/', ArticleList.as_view(), name='article_list'),
    # ... 其他路由。
]
英文:

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

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

    def get_queryset(self):
        user_id = self.kwargs.get(&#39;user_id&#39;)
        if user_id:
            articles = Article.objects.filter(Q(author_id=user_id) | Q(author=self.request.user))
            return articles
        return self.queryset

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


from django.urls import path
from .views import ArticleList

urlpatterns = [
    path(&#39;articles/&lt;int:user_id&gt;/&#39;, ArticleList.as_view(), name=&#39;article_list&#39;),
    # ... Other routes.
]

答案2

得分: 1

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

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

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

class ArticleList(ListAPIView):
queryset = Article.objects.all()
serializer_class = ArticleSerializer
def get_queryset(self):
username = self.request.query_params.get(&#39;username&#39;)
if username:
return User.objects.filter(username=username).article_set.all()
user = self.request.user
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:

确定