[Django]-How to filter a property in Django

2👍

You don’t have any field named organization_id in you model Member, that’s why the error.

Intead you might want this :

result_list = []
memberList = Member.objects.all()

for item in memberList :
    if item.organization_id() == '1' :
        result_list.append(item)

print result_list 

The resultant list result_list will contain all the required objects of model Member.

Thanks.

0👍

According to what I understood from your questions, I assumeed that you have Two Model class.

Lets make example

class Organization(models.Model):
    name = models.CharField(max_length=30)

class Member(models.Model):
    username = models.CharField(blank=True, max_length=30)
    team = models.ForeignKey(Organization)

You use UUIDField as Primary Key. I omitted it. Django make primary key field automatically. I am curious what was your purpose to use UUID Field in the first place.

Anyway, if you create Organization first time. PK number will be 1.

Lets say you are testing in python shell

python manage.py shell
>> import your models
>> Organization.objects.create(name="test1")

then you can connect this Organization with Foreign Key relationship.

>> organization = Organization.objects.get(name="test1")
>> Member.objects.create(username="bob", team=organization)

Next time if you want to get members who in test1 organization.

>> organization = Organization.objects.get(name="test1")
>> Member.objects.filter(team=organization)

or just put PK number of organization ‘test1’. Let’s say it’s 1

>> Member.objects.filter(team=1)

If fixed that you only want to get members who have organization ‘1’, you can add custom manager in model.

class OrganizationManager(models.Manager):
    def get_queryset(self):
        return super().get_queryset().filter(team=1)

class Organization(models.Model):
    name = models.CharField(max_length=30)

class Member(models.Model):
    username = models.CharField(blank=True, max_length=30)
    team = models.ForeignKey(Organization)

    objects = models.Manager()
    organization = OrganizationManager()

you can get members like below

>> Member.organization.all()

it will return members who are in organization pk 1.

0👍

memberList = Member.objects.all().annotate(org_id=F('calculate organization id over other model fields')).filter(org_id='1')

in my case this helps, there F is

from django.db.models import F
👤mixo

Leave a comment