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!
If I understand it correctly, you want to obtain all the Customer
s 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()
Note that since a User
can belong to several groups at the same time, it is thus possible that you obtain Customer
s that belong to different accountOwner
s. For example if the logged in user belongs to both the DOGS and CATS group, you thus will obtain Customer
s that belong to the DOGS group as well as Customer
s that belong to the CATS group.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.