简体   繁体   中英

How to make foreign key accept field value instead of its id in django?

I have created a checkbox for content filtering of products based on category.So when the user clicks on any checkbox only the books with that category should be shown.In the view I am passing the value of checkbox field(category name) obtained from the template but upon filtering, the foreign key is expecting pk(id) instead of field value.I am getting error like this, invalid literal for int() with base 10: '<category name>' .So is it possible to make foreign key accept value instead of id?

Models.py,

class Add_cat(models.Model):
    category = models.CharField("Name",max_length=25,unique=True)

    def __unicode__(self):
        return u'{0}'.format(self.category)

class Add_prod(models.Model):
    book = models.CharField("Book Name",max_length=40)
    author = models.CharField("Author",max_length=30)
    price = models.PositiveIntegerField("Price")
    image = models.ImageField(upload_to='images',null=True)
    cat = models.ForeignKey(Add_cat,on_delete=models.PROTECT)

Template file,

{% for i in products %}
                <input type="checkbox" name="cat_name" value="{{i.cat}}">{{i.cat}}<br>  
{% endfor %}

Views.py,

def welcome_user(request):        
    if 'cat_name' in request.GET:
        filter_category = request.GET.get('cat_name')
        my_products = Add_prod.objects.filter(cat__in = filter_category) 
        context = { "products":my_products}
    else:
        my_products = Add_prod.objects.all()
        context = { "products":my_products}
    return render(request,"welcome-user.html",context)

You can check in the category field itself:

my_products = Add_prod.objects.filter(cat__category__in=filter_category)

Have a look at the documentation on how this works.


Above, is only applicable if filter_category is a list . If it is a string you can filter like following:

my_products = Add_prod.objects.filter(cat__category=filter_category)

您可以尝试一下,它将为您提供帮助:

Add_prod.objects.filter(cat__category = filter_category)

There are two things wrong with your code

  1. You need to look up the field rather than the foreign key
  2. By using __in you are looking the category is equal to any one of the characters in the filter_category .

Hence to fix, use the field lookup and remove the __in

Add_prod.objects.filter(cat__category=filter_category) 

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