'How to get data that belongs to specific user in Django Rest Framework?
I haved Format_List model with relation with Django user and now I want to get the data belongs to specific user by giving user id or after user login.
models.py
class Format_List(models.Model):
class Meta:
db_table = 'format_list'
verbose_name = 'List of Format'
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_family')
image_format = models.ManyToManyField(Format_Image)
format_name = models.CharField(max_length=200)
def __str__(self):
return self.format_name
I am confused that how to write a API(Serializer and View) so that I can get above model data by giving specific user id in request.
I have tried this How to retrieve all models data by User id in Django Serializer?t
But in my case I want to get data assigned to each user by Admin user by giving ID in request.
Any help will be appreciated!
Solution 1:[1]
If you are using modelViewSet in views.py you can overwrite queryset for your model by:
def get_queryset(self):
user = self.request.user
queryset = self.model.objects.filter(user=user)
return queryset
Then you can perform CRUD operations only on this queryset
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Kumail Raza |