django 我如何获得request.user和特定用户的记录(特定模型的)?

atmip9wb  于 2023-02-10  发布在  Go
关注(0)|答案(3)|浏览(131)

我不是很专业的django休息...
我用djangorest框架写了一个博客,例如,当我想获取与文章模型相关的所有记录或获取特定的文章时,没有问题
但我想做的是在单击用户名时向视图发送用户id(或用户名)。
并且作为结果显示与请求用户相关的Article模型的所有记录以及与其名字被点击的用户相关的Article模型的所有记录。
事实上,我想点击每个用户的名字,除了获得该用户的文章,与该请求相关的文章。用户也将采取
这是我目前所做的...

#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']
gojuced7

gojuced71#

您应该直接使用Q对象在get_queryset()方法中进行一些修改,以便:

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'),
    # ... Other routes.
]
8fq7wneg

8fq7wneg2#

views.py

from django.contrib.auth import get_user_model

class CustomArticleList(ListAPIView):
    serializer_class = ArticleSerializer

    def get_queryset(self):
        user_id = self.kwargs.get('user_id')
        username = self.kwargs.get('username')

        request_user = self.request.user
        articles = Article.objects.filter(author=request_user)

        if user_id:
            user = get_user_model().objects.get(id=user_id)
        elif username:
            user = get_user_model().objects.get(username=username)

        articles |= Article.objects.filter(author=user)

        return articles

urls.py

from .views import CustomArticleList

urlpatterns = [
    path('articles/<int:user_id>/', CustomArticleList.as_view(), name='custom-article-list'),
    path('articles/<str:username>/', CustomArticleList.as_view(), name='custom-article-list'),
    # ...
]
omvjsjqw

omvjsjqw3#

示例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('username')
        if username:
           return User.objects.filter(username=username).article_set.all()
        user = self.request.user
        return Article.objects.filter(author=user)

相关问题