Annotate a List of Values

16 views
Skip to first unread message

Matthew Pava

unread,
Nov 17, 2016, 2:26:34 PM11/17/16
to django...@googlegroups.com

I am trying to annotate a list of values on a queryset.

Basically, I have a model of Items that are associated many to many to Serial Numbers, and I want for each distinct Item the list of all Serial Numbers for that Item.

Nate Granatir

unread,
Nov 18, 2016, 9:59:27 AM11/18/16
to Django users, Matthe...@iss.com
As demonstrated here: https://docs.djangoproject.com/en/1.10/topics/db/examples/many_to_many/
If you have a ManyToMany relationship set up in your models, say:

class SerialNumber(models.Model):
    serial = models.CharField(max_length=50)

class Item(models.Model):
    item_name = models.CharField(max_length=100)
    serial_numbers = models.ManyToManyField(SerialNumber)

Then you can get a list of all serials for an item with:

item.serial_numbers.all()
Reply all
Reply to author
Forward
0 new messages