我有以下型号:
class TradeList(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, unique=True)
text = models.TextField(null=True, blank=True)
modified = models.DateTimeField(auto_now=True)
class Meta:
ordering = ['-modified']
def __str__(self):
return "{}'s trade list".format(self.user.username)
def get_absolute_url(self):
return reverse('tradelist_detail', kwargs={'username': self.user.username})
class TradeItem(models.Model):
tradelist = models.ForeignKey('TradeList')
card = models.ForeignKey('cards.Card')
quantity = models.PositiveSmallIntegerField()
class Meta:
abstract = True
class ForTrade(TradeItem):
class Meta:
verbose_name_plural = 'for trade'
ordering = ['card']
class LookingFor(TradeItem):
class Meta:
verbose_name_plural = 'looking for'
ordering = ['card']
我希望能够从我的网站搜索这些模型,所以我创建了一个这样的表单:
class TradeListSearchForm(forms.Form):
for_trade = forms.ModelMultipleChoiceField(queryset=Card.objects.all())
我使用通用FormView来处理表单,所以我重写了它的form_valid
方法,以便在成功验证表单时自定义行为:
class TradeListSearchView(FormView):
form_class = TradeListSearchForm
template_name = 'trades/tradelist_search.html'
def form_valid(self, form):
search_results = TradeList.objects.filter(fortrade__card__in=form.cleaned_data['for_trade'])
return self.render_to_response(self.get_context_data(form=form,
search_results=search_results))
除了一件事,这很有效。此时,用户可以选择多个卡进行搜索,并且该视图搜索具有任何这些特定卡进行交易的所有交易列表。但是我希望能够进行搜索,它只查找那些选择了所有卡进行交易的交易列表,但我想不出怎么做。
答案 0 :(得分:2)
我认为你可以使用一点魔力:
这条线就是杀死你的热潮:
search_results = TradeList.objects.filter(fortrade__card__in=form.cleaned_data['for_trade'])
而不是它,使用:(注意我明确地过滤了TradeList实例多次)
for_trade = form.cleaned_data['for_trade']
search_results = Tradelist.objects.all()
for card in for_trade:
search_results = search_results.filter(fortrade__card__id=card.id)
这样,您就可以为所有卡片过滤所有对象。以前你回来(正如你已经说过的)每个在你选择中有一张牌的商品清单。