0

I am trying to grab all the groups that a user is a member of. here are the relevant files:

groups.models

from django.db import models
from django.contrib.auth.models import User

class Group(models.Model):
    name = models.CharField(max_length=255, unique=True)
    description = models.TextField(blank=True, default='')
    image = models.ImageField(upload_to='images/')
    members = models.ManyToManyField(User)


    def __str__(self):
        return self.name

accounts/views.py

def profile(request, user_id):
    user = get_object_or_404(User, pk=user_id)


    groups = Group.objects.filter(???)

    return render(request, 'accounts/profile.html', {'user':user})

I'm a bit of a newbie when it comes to querying, any help would be really appreciated!

Nader
  • 67
  • 9
  • members is a list! wont you have to iterate though the list? – Nader May 04 '18 at 10:15
  • 1
    You might want to choose a different class name because there already is a Group model: https://docs.djangoproject.com/en/2.0/ref/contrib/auth/#group-model - it's similar to yours, so it might serve as inspiration and the sample code for it might give you answers to your questions. See also: https://stackoverflow.com/questions/4789021/in-django-how-do-i-check-if-a-user-is-in-a-certain-group#20110261 – Risadinha May 04 '18 at 10:23

2 Answers2

1

You can use 'group_set' for particular user to fetch all the related groups.

user = get_object_or_404(User, pk=user_id)
groups = user.group_set.all()

I think this will solve your problem.

Sijan Bhandari
  • 2,941
  • 3
  • 23
  • 36
0

Try it like this:

groups = Group.objects.filter(members=request.user)
Ashish Acharya
  • 3,349
  • 1
  • 16
  • 25