-1

I have two models connected by a many-to-many relationship in django.

class BuildingMapping(models.Model):

    name = models.CharField(max_length=1000, null=False)
    buildings = models.ManyToManyField(
        Building, related_name="mapping"
    )

class Building(models.Model):
    function = models.CharField(
        max_length=1000, blank=True, null=True
    )

Function is a string containing one or more identifier divieded by a "/" e. g. "1300", "1300/2200", "1300/2230/7500", ...

I now want to perform a query that gets only BuildingMapping instances where the function for all Buildings is identical. I tried the following, but this will also return BuildingMapping instances where only one Building has "1300" as function.

BuildingMapping.objects.filter(buildings__function="1300")

Thanks!

Piddy
  • 1
  • Does this answer your question? [Django filter queryset \_\_in for \*every\* item in list](https://stackoverflow.com/questions/8618068/django-filter-queryset-in-for-every-item-in-list) – wfehr Feb 24 '20 at 11:54

2 Answers2

0

If I understood correct, you want to get function field contains "1300". If it is right: BuildingMapping.objects.filter(buildings__function__contains="1300")

kamilyrb
  • 2,502
  • 3
  • 10
  • 25
  • What I understood is he wants to get the `BuildingMapping` which has *all* the required `Building`-instances from a list of ids. – wfehr Feb 24 '20 at 11:57
0

I see that you are trying to fetch all the results which are matching 1300. What you are doing is exact match

strong text

You need to use icontains(case insensitive) or contains(case sensitive) for getting all matched data

enter image description here

Hanny
  • 51
  • 3