Home > Back-end >  Query for favorites of user in Django
Query for favorites of user in Django

Time:09-16

I want to query for the favorites a user has in Django. Every user has a profile (userprofile) and the favorites are stored in this userprofile Model. I want to be able to query for the favorites (they are userprofiles) only using the id of the user. This is what I have but does not work (it returns an empty query even though the user has 3 favorites):

favorites = UserProfile.objects.filter(favorites__user__id=user_id)

My User Model:

class User(AbstractUser):
  usertype = models.PositiveSmallIntegerField(choices=constants.USER_TYPE_CHOICES )
  profile = models.OneToOneField(UserProfile, on_delete=models.CASCADE, primary_key=False)
  token = models.CharField(max_length=10, default='')

My UserProfile Model:

class UserProfile(models.Model):
  birth_date = models.DateField(default=datetime.date(1900, 1, 1))
  favorites = models.ManyToManyField('self', symmetrical=False)

How should I do this? Thank you a lot!

CodePudding user response:

favorites = User.objects.get(id=user_id).profile.favorites.all()
  • Related