如果我有要过滤的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)
答案 0 :(得分:1)
这样做你想要的吗?
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)