Home > Mobile >  Filtering a Model with a Foreignkey with a list of other models?
Filtering a Model with a Foreignkey with a list of other models?

Time:03-09

I want to filter the org collectors by their foreign key org_data by a list of org_data with the Github type.

OrgCollector.objects.filter(
org_data=OrgData.objects.filter(
            data_type=DataTypeEnum.GITHUB
        ))

I currently have this but it does not work. What do I do instead?

Running through the list with a for loop works, but I expect that there is a better way.

I also tried org_data__in but that did not seem to work either.

CodePudding user response:

You can filter with:

OrgCollector.objects.filter(
    org_data__data_type=DataTypeEnum.GITHUB
)

this will look "through" the relation and thus retrieve OrgCollectors for which the data_type of the org_data is DataTypeEnum.GITHUB.

CodePudding user response:

If I understood your question correctly and you have added the correct code, this is what you can do:

# Get ids of org_data
org_data_ids = OrgData.objects.filter(
            data_type=DataTypeEnum.GITHUB
        ).values_list('id', flat=True)

result = OrgCollector.objects.filter(org_data_id__in=org_data_ids)

or

# If the above one is creating duplicate results
result = OrgCollector.objects.filter(org_data_id__in=org_data_ids).distinct()

CodePudding user response:

In the enum type, it is not matching with the string but with the enum type.

Try this query

OrgCollector.objects.filter(
org_data=OrgData.objects.filter(
            data_type=DataTypeEnum.GITHUB.value
        ))
  • Related