简体   繁体   中英

Django many-to-many query matching all related fields

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 "/" eg "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!

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

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

在此处输入图片说明

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM