Before in my models.py I had
report_division = models.TextField(blank=True, max_length=40)
and I counted by filter using this line in my views.py:
CRS = Post.objects.filter(report_division='Something').count()
Now I have a seperate class in my models.py
class Divizija(models.Model):
naziv_divizija = models.CharField(max_length=40)
def __str__(self):
return self.naziv_divizija
class Post(models.Model):
report_division = models.ForeignKey(Divizija, on_delete=models.SET_NULL, null=True,
verbose_name="Divizija")
I can't get my query to work now. I tried:
CRS = Post.objects.filter(report_division=1).count()
CRS = Post.objects.filter(report_division_id=1).count()
CRS = Post.objects.filter(report_division='Something').count()
CodePudding user response:
You have to specify the field of the foreign key you want to filter by
CRS = Post.objects.filter(report_division__naziv_divizija=1).count()
CRS = Post.objects.filter(report_division_id=1).count() # this one is right
CRS = Post.objects.filter(report_division__naziv_divizija='Something').count()