簡體   English   中英

Django篩選器推論出ManyToMany

[英]Django Filter deduce ManyToMany

在Tag字段上具有多對多關系的簡單模型。

class Tag(models.Model):
    description = models.TextField()

class Species(models.Model):
    name = models.CharField(max_length=256)
    tags = models.ManyToManyField(Tag)

現在我正在嘗試這樣做,據我所知,它應該返回一個與標簽列表中的每個tag_description匹配的列表:

tag_list = request.GET.get('q').split(',')
species = Species.objects.filter(reduce(and_, [Q(tags__description=c) for c in tag_list]))

但是它返回一個空列表。 它應該返回一些對象。

我只給一個標簽就可以了

知道為什么會這樣嗎?

我正在使用它,如此答案所示: https : //stackoverflow.com/a/8636836/228660

正如您在該問題的注釋中實際看到的那樣,它實際上並不起作用;)問題是,您將對所有過濾器使用相同的聯接(表示相同的對象)。 除非tag_list中的所有項目都相同,否則將永遠無法使用。 問題出在Q對象內,而不是完全過濾的查詢內。

tag_list = request.GET.get('q').split(',')

# Generate a query with all species
all_species = Species.objects.all()
# Generate a list with the separately filtered species
filtered_species = [all_species.filter(tags__description=c) for c in tag_list]
# Join the filtered species together using the same method :)
species = reduce(and_, filtered_species, all_species)

我認為另一種方式是:

tag_list = request.GET.get('q').split(',')
species = Species.objects.all().distinct()
for tag in tag_list:
    species = species.filter(tags__description=tag)
else:
    species = Species.objects.none()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM