Home > Enterprise >  Django filter for ForeignKey included in ManyToMany
Django filter for ForeignKey included in ManyToMany

Time:05-05

I don't know if I'm tired or if the answer is simple but I don't see it

I have a model like this:


class Company(models.Model):
    name = models.CharField(max_length=32, unique=True)
    

class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    company_admin = models.ManyToManyField(Company)
    # ...


class GroupData(models.Model):
    name = models.CharField(max_length=32)
    company = models.ForeignKey(
        Company, on_delete=models.CASCADE)

If in a view I do:

print(request.user.userprofile.company_admin.all())

...I get a QS with of all the companies to which the user belongs, and are Ok.

What I need is to get a filter for GroupData where company 'is included' into this QS in order to get only objects of GroupData based on user 'company_admin' right.

Can anyone help me to understand how to get this filter?

Great thanks

CodePudding user response:

If I understand the requirement:

user_company_pks = users_profile.company_admin.all().values_list( 'pk', flat=True)

filtered_groupdata = Groupdata.objects.filter( company__pk__in=user_company_pks )

The first returns a list of pks. The second filters groupdata objects that have a company with a pk in that list

It might be worth investigating whether

 filtered_groupdata = Groupdata.objects.filter( company_id__in=user_company_pks )

(a) works and (b) is significantly any more efficient. The value of a foreign key (company_id) is usually the pk of the related object.

  • Related