Я бы хотел получить все профили, где tag = 'hello' и tag = 'world'. Я пытался с Q () запрос, но у меня нет правильного результата.
models.py
class Tag(models.Model):
name = models.CharField(unique=True, max_length=100)
slug = models.SlugField(unique=True, max_length=100)
def __str__(self):
return self.name
class Meta:
ordering = ['slug']
class Profile(models.Model):
name = models.CharField(max_length=100)
tags = models.ManyToManyField(Tag)
def __str__(self):
return self.name
class Meta:
ordering = ['name']
views.py
def search(request: HttpRequest):
q_tag_list = request.GET.get('search-tag').split(',')
profile_filter = Q()
for tag in q_tag_list:
profile_filter = profile_filter & Q(tags__slug__startswith=tag)
profiles = Profile.objects.filter(profile_filter)
return render(request, 'list.html', {'profiles': profiles})
sql сгенерировано (из панели отладки django)
SELECT "socialmedia_profile"."id", "socialmedia_profile"."name", "socialmedia_profile"."facebook_name", "socialmedia_profile"."facebook_latest_likes" FROM "socialmedia_profile" INNER JOIN "socialmedia_profile_tags" ON ("socialmedia_profile"."id" = "socialmedia_profile_tags"."profile_id") INNER JOIN "socialmedia_tag" ON ("socialmedia_profile_tags"."tag_id" = "socialmedia_tag"."id") WHERE ("socialmedia_tag"."slug" LIKE '''hello%''' ESCAPE '\' AND "socialmedia_tag"."slug" LIKE '''world%''' ESCAPE '\') ORDER BY "socialmedia_profile"."name" ASC