Reputation: 129
I'm trying to filter objects based on a foreign key and I'm getting that error. When I use int( id of categories) the code below works. How can I make it work for strings?
models.py:
from django.db import models
# Create your models here.
class Category(models.Model):
category_name=models.CharField(max_length=40)
def __str__(self):
return self.category_name
class dash(models.Model):
title=models.CharField(max_length=40)
card_pic=models.ImageField(upload_to="dash_pics/")
embed_tag=models.TextField()
category=models.ForeignKey(Category,on_delete=models.CASCADE)
objects = models.Manager()
def __str__(self):
return self.title
views.py:
def students(request):
stu_dashboards = models.dash.objects.filter(category='Students')
return render(request,'dashboards/students.html',{'dashboards':stu_dashboards})
Upvotes: 1
Views: 1468
Reputation: 477180
You can not filter with category='Students'
, since category
is a ForeignKey
to the Category
model.
You can however filter on the category_name
, with:
def students(request):
stu_dashboards = models.dash.objects.filter(category__category_name='Students')
return render(request,'dashboards/students.html',{'dashboards':stu_dashboards})
Note: Normally model fields have no prefix with the name of the model. This makes queries longer to read, and often want uses inheritance of (abstract) models to inherit fields, so using a prefix would make it less reusable. Therefore it might be better to rename your field
tocategory_name
name
.
Upvotes: 1