0

I have a model Subjects

#models.py

class Subjects(models.Model)
    ....
    name = models.ForeignKey(User, unique=False)
    ....
    number_of_followers = models.IntegerField( I want to have something like this: SELECT COUNT( DISTINCT name ) FROM school_subjects; ) 

I don't really know if I can do this inside IntegerField or I have to add this to save method.

Thank you in advance.

1
  • 1
    Django book has answers to all sorts of these simple questions: djangobook.com/en/2.0 Commented Aug 7, 2012 at 0:20

2 Answers 2

2

Something like this (using count())?

Subjects.objects.all().count()
Sign up to request clarification or add additional context in comments.

2 Comments

Yes, that's correct, BUT how can I update number_of_followers inside models.py? In other words, when the object gets created, I want this field to be field automatically.
So you want to save the total number of distinct Subject objects into the number_of_followers field of every Subject object? I think it would be better to just make a method that calculates that dynamically
0

Try this:

school_subjects.objects.all().distinct('name').count()

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.