如何使用 slug 来“objects.filter”通过多对多类检索数据

问题描述

我是 django 和编码的新手,所以在我的脑海里有这个问题,我有两个方向,我不知道这是否是正确的解决方案。

所以我在 model.py 中有三个类 Recipe IngredientIngredientAmount 其中,

  • Recipe一个 ManyToManyField 连接到 Ingredient 并且有 SlugField 被我的 recipe_detail.html 页面使用基于详细功能的视图获取.
  • IngredientAmount 可以说是一个“通过”类,并且有 RecipeIngredient 作为 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 个可能的解决方案(可能完全不可行) - 并提出了一个问题:

  1. 有没有办法通过我的 m2m-through 类(如我的 recipe 类(带/不带 related_name))调用它的 slug 从 Recipe 模型中检索诸如 IngredientAmount 之类的相关对象?

我一直在寻找的推导:related_objects in m2mm2m-through class

  1. 或者我是否必须在我的 SlugField 类中制作一个 IngredientAmount 以某种方式将我的 recipe_id 更改为 slug?如果是这样,我该怎么做?

我希望所有这些都有意义。我会很感激任何能指出我正确方向的事情。我很不知道如何解决这个问题。使用 objects.filter(id=[num]) 和如何从 m2m 中检索数据为 _set 有很多 - 但不知道什么时候作为 slug 和 m2m-通过模型。如果我的代码或问题是垃圾,我提前道歉 - 如果我能澄清任何事情,请告诉我。谢谢!

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)