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

Question:

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']
Asked By: Mehdi

||

Answers:

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'),
    # ...
]
Answered By: Nikhil Kotiya

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('user_id')
        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('articles/<int:user_id>/', ArticleList.as_view(), name='article_list'),
    # ... Other routes.
]
Answered By: Sunderam Dubey

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