I have this models.py
class Sitename(models.Model):
#id = models.AutoField(primary_key=True) ## to be removed
site = models.CharField() ## find values
class Equipment(models.Model):
#id = models.AutoField(primary_key=True) ## to be removed
serialno = models.CharField() ## known values
class RSL(models.Model): ##Radio Station License
#id = models.AutoField(primary_key=True) ## to be removed
sitename = models.ForeignKey(Sitename)
equipment = models.ManyToManyField(Equipment)
I only know the Equipment
serialno
, I can't figure out the proper queryset? So far I know how to query a foreignkey.
sn = 'abc'
equip = Equipment.objects.get(serialno=sn)
rsl = RSL.objects.?????
sitename = Site.objects.get(pk=rsl.pk)
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.