[Answer]-Django queryset ManytoMany and OnetoMany


You know the equipment serial no., so use –

equip = Equipment.objects.get(serialno=sn)

Because your equipment field of RSL class and Equipment class are a Many2Many relation, there maybe more than one RSL class objects related to one Equipment object. To get the queryset, use –

rsl_queryset = equip.rsl_set.all()

(Please check whether rsl_set is a method of equip object by checking if it is listed in dir(equip). Looking at your model, most probably it is. BTW, you can change it to the name you want by adding related_name = “name you want” to the definition.
For eg: –

equipment = models.ManyToManyField(Equipment, related_name = "rsl_objects")

This way you can access it by rsl_queryset = equip.rsl_objects.all())

Now you have got a queryset containing RSL objects related to equip object. So, iterate over them to get the values you want –

for rsl_object in rsl_queryset:
    print "site = " + rsl_object.sitename.site

Leave a comment