开发者社区> 问答> 正文

获取ManyToManyField的条目

我正在使用ManyToManyField并在表单上使用ModelMultipleChoice,我想获取条目,但我得到的只是 appname.Extra.none

models.py

class Extra(models.Model):

extra_n = models.CharField(max_length=200)
extra_price = models.IntegerField(default=0)

def __str__(self):
    return self.extra_n

class Meal(models.Model):

restaurant = models.ForeignKey(Restaurant, on_delete=models.PROTECT)
category = models.ForeignKey(MealCategory, on_delete=models.PROTECT)
name = models.CharField(max_length=500)
short_description = models.CharField(max_length=500)
image = models.ImageField(upload_to='meal_images/', blank=False)
price = models.IntegerField(default=0)
extras = models.ManyToManyField(Extra, related_name='extras')
def __str__(self):
    return self.name

forms.py

class MealForm(forms.ModelForm):

extras = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple(), queryset=Meal.extras)

class Meta:
    model = Meal
    exclude = ("restaurant",)

views.py

def restaurant_meal(request):

meals = Meal.objects.filter(restaurant = request.user.restaurant).order_by("-id")
return render(request, 'restaurant/meal.html', {"meals": meals})  

所需的输出是在restaurant_meal视图上显示添加的额外内容。

展开
收起
一码平川MACHEL 2019-01-18 10:22:24 1511 0
1 条回答
写回答
取消 提交回答
  • 你可以尝试改变

    meals = Meal.objects.filter(restaurant = request.user.restaurant).order_by("-id")

    meals = Meal.objects.filter(restaurant = request.user.restaurant).prefetch_related('extras').order_by("-id")
    然后再试一次。

    2019-07-17 23:25:49
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载