1

I want to know how to count the number of "keys" a "keyboard"

class Key(models.Model):
    name = models.CharField(max_length = 20)

class Keyboard(models.Model):
    name = models.CharField(max_length = 20)
    keys = models.ManyToManyField(Key)

I found a similar question but do not know if it can be modified for what I need, which is how many eleementos form a ManyToMany

count values from manytomanyfield

Community
  • 1
  • 1

1 Answers1

1

To get the count of keys objects associated with a Keyboard instance, you can use .count()

keyboard_object.keys.all() gives the associated Key instances for a keyboard_object.

We now apply .count() on it to get the number of Key objects associated with it.

keyboard_object.keys.all().count() # gives the count

(Even keyboard_object.keys.count() will work unless the default Key queryset is changed.)

Rahul Gupta
  • 46,769
  • 10
  • 112
  • 126
  • 1
    in addition, unless you change the default queryset of the `Key` model, you can avoid the `.all()` and just do `keyboard_object.keys.count() ` :) – Gerard Aug 10 '15 at 19:41