我正在学习Django并使用ForeignKey链接我的模型。 icontains在不是ForeignKeys的字段中工作。
我想过滤模型中的Items,只显示与查询集匹配的字段。 但是提出了查询集:相关字段无效查找:icontains
请帮忙。下面是我的模型和视图
我的模特
class Category(models.Model):
category = models.CharField(max_length=200, default='', blank=True, null=True)
def __unicode__(self):
return self.category
class StoreItems(models.Model):
item_name = models.CharField(max_length=200, default='', blank=True, null=True)
def __unicode__(self):
return self.item_name
class Supplier(models.Model):
supplier_name = models.CharField(max_length=200, default='', blank=True, null=True)
def __unicode__(self):
return self.supplier_name
class Unit(models.Model):
unit = models.CharField(max_length=200, default='', blank=True, null=True)
def __unicode__(self):
return self.unit
class Store(models.Model):
category = models.ForeignKey(Category, blank=True, null=True)
item_name = models.ForeignKey(StoreItems, blank=True, null=True)
quantity = models.IntegerField(default='', blank=True, null=False)
receive_amount = models.IntegerField(blank=True, null=True)
receive_by = models.CharField(max_length=120, default='', blank=True, null=False)
issue_amount = models.IntegerField(blank=True, null=True)
issue_by = models.CharField(max_length=120, default='', blank=True, null=True)
issue_to = models.CharField(max_length=120, default='', blank=True, null=True)
supplier_name = models.ForeignKey(Supplier, blank=True, null=True)
created_by = models.CharField(max_length=15, default='', blank=True, null=True)
unit = models.ForeignKey(Unit, blank=True, null=True)
reorder_level = models.IntegerField(default='0', blank=True, null=False)
export_to_CSV = models.BooleanField(default=False)
last_updated = models.DateTimeField(auto_now_add=False, auto_now=True)
我的观点
def store_list(request):
label = 'STORE'
title = 'Select the item you want to filter'
heading = 'SEARCH ITEMS'
if request.user.is_authenticated():
form = StoreSearchForm(request.POST or None)
context = {
"title": title,
"form": form,
"heading": heading,
}
if request.method == 'POST':
queryset = Store.objects.all().order_by('item_name').filter(category__icontains=form['category'].value(), item_name__icontains=form['item_name'].value())
context = {
"queryset": queryset,
"form": form,
}
return render(request, "store.html", context)
答案 0 :(得分:4)
是的,你不能直接在外键上使用icontains但是......
Store.objects.all().order_by('item_name'
).filter(category__category__icontains=form['category'].value(), item_name__icontains=form['item_name'].value())
您的类别模型包含一个也称为类别的字段。这可以作为category__category
访问,这意味着您可以使用上面给出的查询。