如何在 Django 中生成查询?

How to generate query in Django?

如果我有要过滤的 ID 列表,我该如何生成查询?例如:

[14, 44] 会导致 query.filter(tags__tag_id=14).filter(tags__tag_id=44)

>>> print(Place.objects.filter(tags__tag_id=14).filter(tags__tag_id=44).query)

SELECT "places_place"."id", "places_place"."address"
FROM "places_place"
INNER JOIN "places_placetag"
ON ("places_place"."id" = "places_placetag"."place_id")
INNER JOIN "places_placetag"
T4 ON ("places_place"."id" = T4."place_id")
WHERE ("places_placetag"."tag_id" = 14 AND T4."tag_id" = 44)

(我不知道上面SQL中的T4是什么,但没关系,那是另一个问题)

我有一个 hacky 的解决方案,但它太天真而且看起来很糟糕,必须有更好的方法来实现它:

tag_ids = [14, 44]

query_string = 'Place.objects'
for tag_id in tag_ids:
    query_string += ('.filter(tags___tag_id=' + str(tag_id))

query = eval(query_string)

class Place(models.Model):
    address = models.CharField(max_length=123)

class PlaceTag(models.Model):
    place = models.ForeignKey('Place', models.CASCADE, 'tags')
    tag = models.ForeignKey('Tag', models.CASCADE, 'places')

class Tag(models.Model):
    tag = models.CharField(max_length=254)

这是你想要的吗?

tag_ids = [11, 22, 33]  # Place must have all of these tags
query = Place.objects.all()
for tag_id in tag_ids:
    query = query.filter(tags___tag_id=tag_id)