0

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()
2
  • 1
    second one should work Post.objects.filter(report_division_id=1).count() what do you mean by not working is it giving you an error or is it not giving you the correct count? Commented Nov 9, 2021 at 17:30
  • It's working, donno why I didn't at start, maybe my mistake. Thank you for your reply. Commented Nov 9, 2021 at 17:37

1 Answer 1

1

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()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.