The title is probably confusing but I didn’t know how else to paraphrase it. Here is an example.
Is it better to do something like this
class UserType( models.Model ) :
def user_count( self ) :
return self.userprofile_set.count()
or like this?
class UserType( models.Model ) :
def user_count( self ) :
# Does "user_types = self" work? I'm not sure.
return UserProfile.filter( user_types = self.pk ).count()
where
class UserProfile( models.Model ) :
user_types = models.ManyToManyField( UserType )
UserType.user_count() simply returns the number of UserProfile who has a particular UserType.
Sorry if this is a stupid, trivial question, but I was curious. Perhaps some Django expert can dig in on the actual SQL performance or something :-).
They are the same. Choose whatever you like.
In my opinion the first looks cleaner. The second seems a bit incorrect because user_types is not a single pk value.
By the way, it is recommended to always specify a related_name attribute.
For example if it would be:
and then:
Looks even cleaner.
But both statements generate the same sql, we just could say that first is the shortcut for second. So it’s not about sql-performance