如何解决如何使用 slug 来“objects.filter”通过多对多类检索数据
我是 django 和编码的新手,所以在我的脑海里有这个问题,我有两个方向,我不知道这是否是正确的解决方案。
所以我在 model.py
中有三个类 Recipe
Ingredient
和 IngredientAmount
其中,
-
Recipe
有一个ManyToManyField
连接到Ingredient
并且有SlugField
被我的recipe_detail.html
页面使用基于详细功能的视图获取. -
IngredientAmount
可以说是一个“通过”类,并且有Recipe
和Ingredient
作为ForeignKey
这是我的model.py
:
class Recipe(models.Model):
alphanumeric = RegexValidator(
r'[a-zA-Z][a-zA-Z ]+','Only alphabet characters and spaces are allowed.')
slug = models.SlugField(null=False,unique=True)
title = models.CharField(max_length=30,null=True,validators=[alphanumeric])
description = models.TextField(max_length=200,blank=True)
ingredients = models.ManyToManyField(
'Ingredient',through='IngredientAmount',related_name='recipes')
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('recipe:recipe_detail',kwargs={'slug': self.slug})
class Ingredient(models.Model):
name = models.CharField(max_length=200,null=True)
def __str__(self):
return self.name
class IngredientAmount(models.Model):
SINGLE = 1
DOUBLE = 2
TRIPLE = 3
AMOUNT_CHOICES = (
(SINGLE,'Single'),(DOUBLE,'Double'),(TRIPLE,'Triple'),)
recipe = models.ForeignKey(
'Recipe',related_name='ingredient_amounts',on_delete=models.SET_NULL,null=True)
ingredient = models.ForeignKey(
'Ingredient',blank=True)
amount = models.IntegerField(choices=AMOUNT_CHOICES,default=SINGLE)
def __str__(self):
return f'Recipe = {self.recipe},Ingredient = {self.ingredient},Amount = {self.amount}'
我可以通过抓取弹头并使用 recipe_detail.html
来让我的 {{ recipe.title }}
显示 {{ recipe.description }}
和 context={'recipe':recipe}
def recipeDetail(request,slug):
recipe = get_object_or_404(Recipe,slug=slug)
# r = Recipe.objects.get(slug=slug)
# related_ingredients = r.ingredients_set.all() --> related_ingredients = r.recipes.all() -- will work because of 'related_name' in my Recipe model?
return render(request,'recipe/recipe_detail.html',{'recipe': recipe,'related_ingredients': related_ingredients})
所以我想要做的是使用来自 IngredientAmount 的 context={related_ingredients': related_ingredients}
获取“配方”标题、“成分”名称和“数量”。
我可以像这样在 shell 中使用 pk 来做到这一点:
>>> ia = IngredientAmount.objects.filter(recipe_id=3)
>>> ia
<QuerySet [<IngredientAmount: Recipe = pumpkin with rice,Ingredient = pumpkin,Amount = 1>,<IngredientAmount: Recipe = pumpkin with rice,Ingredient = rice,Amount =
1>]>
但我希望能够通过它的“南瓜饭”来抓住它。
所以回到我脑海中的 2 个可能的解决方案(可能完全不可行) - 并提出了一个问题:
- 有没有办法通过我的 m2m-through 类(如我的
recipe
类(带/不带 related_name))调用它的 slug 从Recipe
模型中检索诸如IngredientAmount
之类的相关对象?
我一直在寻找的推导:related_objects in m2m 和 m2m-through class
- 或者我是否必须在我的
SlugField
类中制作一个IngredientAmount
以某种方式将我的 recipe_id 更改为 slug?如果是这样,我该怎么做?
我希望所有这些都有意义。我会很感激任何能指出我正确方向的事情。我很不知道如何解决这个问题。使用 objects.filter(id=[num]) 和如何从 m2m 中检索数据为 _set
有很多 - 但不知道什么时候作为 slug 和 m2m-通过模型。如果我的代码或问题是垃圾,我提前道歉 - 如果我能澄清任何事情,请告诉我。谢谢!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。