开发者社区> 问答> 正文

获取ManyToManyField的条目

一码平川MACHEL 2019-01-16 16:57:41 497

我正在使用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视图上显示添加的额外内容。

python django django-models django-forms 多对多

Python
分享到
取消 提交回答
全部回答(1)
  • 一码平川MACHEL
    2019-07-17 23:25:40

    你可以尝试改变

    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")
    然后再试一次。

    0 0

集结各类场景实战经验,助你开发运维畅行无忧

推荐文章
相似问题