Bhanukiran Bhanukiran - 10 months ago 42
Python Question

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?,

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="{{}}">{{}}<br>
{% endfor %},

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}
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)