Django query mptt nodes selected by a user

172 Views Asked by At

I am new to Django, I used django-mptt so that users can select different genres. The tree has three levels and user chooses the root node genres in signup. The code for that is

class Genre(MPTTModel):
    name = models.CharField(max_length=50, unique=True)
    parent = TreeForeignKey('self', null=True, blank=True, related_name='children')

    def __unicode__(Self):
         return Self.name

    class MPTTMeta:
         order_insertion_by = ['name']

class UserProfile(BaseModel):
    """
    Profile and configurations for a user
    """
    DEFAULT_PHOTO = 'images/default/profile.png'
    genres = models.ManyToManyField(Genre)

I am stuck with how to show in Users profile page the genres they have selected. How to query the genres selected by a user?

2

There are 2 best solutions below

0
On

Have You tried this?

request.user.genre_set.all()  # All attached genres to the current user.

Or

Genre.objects.filter(userprofile__in=request.user)
0
On

After some effort I figured it out!

{{ request.user.get_profile.genres.all }}