简体   繁体   中英

Searching foreign key field in django

I have been trying to build a search functionality in my app but i have stuck on querying for the foreign key field, as it doesn't return anything and the code shows no error. Below is my code.

forms.py 
class StockSearchForm(forms.ModelForm):
    class Meta:
        model = Stock
        fields = ['category', 'item_name']

My view where i implemented the search

views.py
def list_items(request):
    header = 'List of items'
    form = StockSearchForm(request.POST or None)
    queryset = Stock.objects.all()
    context = {
        "form": form,
        "header": header,
        "queryset": queryset,
    }
    #Searching an item and category
    if request.method == 'POST':
        queryset = Stock.objects.filter(category__name__icontains=form['category'].value(),
                                        item_name__icontains=form['item_name'].value()
            )
        context = {
           "form": form,
           "header": header,
           "queryset": queryset,
        }

    return render(request, "list_items.html", context)

My models are as follows.

models.py
from django.db import models

class Category(models.Model):
    name = models.CharField(max_length=50, blank=True, null=True)
    def __str__(self):
        return self.name

class Stock(models.Model):
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    #category = models.CharField(max_length=50, blank=True, null=True)
    item_name = models.CharField(max_length=50, blank=True, null=True)
    quantity = models.IntegerField(default='0', blank=True, null=True)
    receive_quantity = models.IntegerField(default='0', blank=True, null=True)
    receive_by = models.CharField(max_length=50, blank=True, null=True)
    issue_quantity = models.IntegerField(default='0', blank=True, null=True)
    issue_by = models.CharField(max_length=50, blank=True, null=True)
    issue_to = models.CharField(max_length=50, blank=True, null=True)
    phone_number = models.CharField(max_length=50, blank=True, null=True)
    created_by = models.CharField(max_length=50, blank=True, null=True)
    reorder_level = models.IntegerField(default='0', blank=True, null=True)
    timestamp = models.DateTimeField(auto_now_add=False, auto_now=True)
    last_updated = models.DateTimeField(auto_now_add=True, auto_now=False)
    export_to_CSV = models.BooleanField(default=False)

    def __str__(self):
        return self.item_name + '' + str(self.quantity)

So what happens is, I can search just fine the "item_name" field and results come up as required, but when i attempt to search for category no error pops up but no results show up, i kinda feel it's due to some foreign key fields issues but i can't just figure it out, I will much appreciate some help, this thing has been a nightmare for quite a while.

Try doing the following. I assume the form is not being properly used.

if request.method == 'POST' and form.is_valid():
        queryset = Stock.objects.filter(category__name__icontains=form.cleaned_data.get('category'),
                                        item_name__icontains=form.cleaned_data.get('item_name')
            )

Try this:

queryset=Stock.objects.filter(category__name__icontains=form['category'].value(),
                               item_name__icontains=form['item_name'].value())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM