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
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.)