我的模特 -
class tags(models.Model):
tag_id = models.AutoField(primary_key = True)
tname = models.CharField(max_length = 30, unique = True)
def __unicode__(self):
return u'%s %s' % (str(self.tag_id), self.tname)
class Meta:
ordering = ('tag_id',)
class food(models.Model):
food_id = models.AutoField(primary_key = True)
fname = models.CharField(max_length = 150, unique = True)
image = models.ImageField(default = 'index.png')
tag = models.ManyToManyField('tags')
def __unicode__(self):
return u'%s %s (%s)' % (str(self.food_id), self.fname, ", ".join(t.tname for t in self.tag.all()))
class Meta:
ordering = ('food_id','fname')
class price_list(models.Model):
price_id = models.AutoField(primary_key = True)
rate = models.PositiveSmallIntegerField(default = 0)
h = models.ForeignKey('hotels')
f = models.ForeignKey('food')
def __unicode__(self):
return u'%s %s %s' % (str(self.price_id), self.h.hname, self.f.fname)
我想查询给定酒店所有食物的所有标签。
我试着这样做 -
data['menu'] = list(price_list.objects.filter(h__hotel_id = post['hotel_id']).values('f__fname','f__tag__tname'))
但这给了我像 -
的结果{"menu": [{"f__tag__tname": "Veg", "f__fname": "Paneer Butter Masala"}, {"f__tag__tname": "Indian", "f__fname": "Paneer Butter Masala"}, {"f__tag__tname": "Continental", "f__fname": "Paneer Butter Masala"}]}
我希望我的结果像 -
{"menu": [{"f__tag__tname": ["Veg", "Indian", "Continental"], "f__fname": "Paneer Butter Masala"}]}
我也试过prefetch_related
,但无法获得所需的输出。
感谢任何帮助。
提前致谢。
编辑:
我修改了这样的查询 -
data = {}
data['menu'] = list(price_list.objects.filter(h__hotel_id = post['hotel_id']).values('f__fname'))
i = 0
for d in data['menu']:
data['menu'][i]['tag_list'] = list(food.objects.filter(food_id = d['f__food_id']).values('tag__tname'))
i = i+1
return JsonResponse(data)
它给了我输出 -
{"menu": [{"f__fname": "Paneer Butter Masala", "tag_list": [{"tag__tname": "Veg"}, {"tag__tname": "Indian"}, {"tag__tname": "Continental"}]}]}
不是我想要的,但比以前的输出更好。但我认为我所做的查询效率非常低。
如何优化查询以及如何获得所需的输出,即
{"menu": [{"f__tag__tname": ["Veg", "Indian", "Continental"], "f__fname": "Paneer Butter Masala"}]}
提前致谢。
答案 0 :(得分:0)
尝试这样的事情(将其作为模型的属性):
{:.2f}
另外,我会将你的模型的第一个字母大写。例如,
def get_tnames_fnames(self):
return map(str, self.f.all().values('fname', 'tag__tname', flat=True))