2

I am trying to filter a view related to the group to which the logged in user belongs to.

Lets say we have a user who belongs to a group DOGS. I figured out how to filter for a specific that means known group name = DOGS.

Models.py

from django.contrib.auth.models import Group

    class Customer(models.Model):
        customerName = models.CharField(max_length=50)
        accountOwner = models.ForeignKey(Group, null=True, related_name='usGroup', on_delete=models.SET_NULL )

How do I do that in

views.py:

from django.contrib.auth.models import User, Group

 @login_required
    def home(request):
        myData = Customer.objects.filter("Return only data of the group to which the user belongs".)

Do you have a hint? I only found solutions for filtering a specific groupname but not the property of the logged in user.

Thanks in advance!

kingbrain
  • 116
  • 12

1 Answers1

4

If I understand it correctly, you want to obtain all the Customers with as accountOwner, a Group object to which the logged in User belongs.

A request has a request.user attribute which stores the user that is logged in. We can then filter on this:

@login_required
def home(request):
    myData = Customer.objects.filter(accountOwner__user=request.user)

Note that since a User can belong to several groups at the same time, it is thus possible that you obtain Customers that belong to different accountOwners. For example if the logged in user belongs to both the DOGS and CATS group, you thus will obtain Customers that belong to the DOGS group as well as Customers that belong to the CATS group.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
  • Thank you. I knew that it is easy but I didn't know the answer. What I don't get: Why can I access the user through the Foreign Key relation of 'Group'? – kingbrain Jul 27 '18 at 11:08
  • @kingbrain: because Django always automatically adds an implicit reverse relation. You can obtain the users of a `Group` with `some_group.user_set.all()` for example. In queries, you can thus use `user`. – Willem Van Onsem Jul 27 '18 at 11:10
  • 1
    @Willem_Van_Onsem: Thank you for your reply and sorry for bothering again. Am I right that this is the intrinsic concept of many-to-many-relationships? [Django Model Documentation](https://docs.djangoproject.com/en/2.0/topics/db/models/#module-django.db.models) – kingbrain Jul 27 '18 at 12:47
  • @kingbrain: wel for any type of relation, so `ForeignKey`s, `OneToOne`s, etc. So yes indeed, this is also the case for relations you write yourself. If you thus wrote for example two models `A` and `B`, and `B` has a `ForeignKey` to `A`, then you can query `some_a.b_set.all()` to fetch the relation in reverse. – Willem Van Onsem Jul 27 '18 at 12:48