Skip to content Skip to sidebar Skip to footer

Getting Model Filters To Show Count Of Active Values

I have 2 models that are connected. Model 1 is userprofiles and model 2 is events each user can have multiple events... each event can be active or deactivated. I have a for loop i

Solution 1:

you can try use model propery

in model:

class UserProfile(models.Model):
     # You code here
     @property
     def active_events(self):
         return self.user.events_set.filter(active='a').count()

in template:

{{ kitchen_list.userprofile.active_events }}

Solution 2:

Rather do it in the views.py instead of the template to count then pass the values to the template. Assuming you hva e set up the foreign relations well in the models then in the views do the following: user_profiles = User.objects.filter(profile__user_profile_active='y').filter(is_active=True) counts = user_profiles.events_set.count()

Then pass that as a context. Or you can try creating a method in your model UserProfile:

class UserProfile:
....
def events(self):
    return self.events_set.count()

Post a Comment for "Getting Model Filters To Show Count Of Active Values"