I have users and followers the model looks like this:
class Follow(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="user")
mutual = models.BooleanField(default=False, null=True, blank=True)
follower = models.ForeignKey(User, on_delete=models.CASCADE, related_name="follower")
I want to get all the followers from the user who’s id is that of the logged in user. The documentation does not explain it, or I just don’t understand it correctly so just looking for some guidance pls
Let’s break this down into to parts.
First, assume you have a User
object named user
.
What you’re trying to get are a set of User
, where the members of that set are related to Follow
through the related_name follower
, where those entries of Follow
have a user field = user
.
So, your query is going to be something like User.objects.filter(follower__user=user)
My problem is I’m in too much of a hurry and because there is just so much to read I feel I cannot get to a solution fast enough by spending hours reading and reading. So instead I spend hours searching the Internet trying to find a solution, which in the end is not what I’m looking for. Better to read!!!
One thing I might not have mentioned is that I am using DRF and so it provides you with a bunch of generic views that you can customize and so the solution to my problem was this:
from rest_framework import generics
from rest_framework import permissions
from connections.models import Follow
from rest_framework import serializers
class FollowSerializer(serializers.ModelSerializer):
class Meta:
model = Follow
fields = [
"user",
"mutual",
"follower",
]
class FollowList(generics.ListAPIView):
permission_classes = [permissions.IsAuthenticated]
serializer_class = FollowSerializer
name = 'followers-list'
def get_queryset(self):
return Follow.objects.all().filter(user=self.request.user)
Which works perfectly. I will spend more time reading.
Another question I have pls:
How do I get all the objects from all different models created by a user. So for example say a user have created a car instance, a house instance and a plane instance. How do I show a list with cars, houses and planes together? I want to make just one query instead of writing three different queries, because I want to display them according to date created. So if I created a car at 10am and a house at 11am and a plane at 12pm then I must show in a list car, house, plane. Is this possible or must I write three queries and then add the items to a list and then traverse that list?
Thanks for your help