【问题标题】:Accessing primary key in Django class based view在基于 Django 类的视图中访问主键
【发布时间】:2021-07-01 13:51:24
【问题描述】:

在基于 Django 类的视图中访问主键

让我们从头开始。我有 2 个模型,配方和成分。它们看起来像这样。

在models.py中

class Recipe(models.Model):
    name=models.CharField(max_length=20, help_text='Enter the name of this recipe')
    description=models.TextField(max_length=75, help_text='Describe your recipe')
    
    def __str__(self):
        return self.name
    
    def get_absolute_url(self):
        return reverse('recipe-detail', kwargs={'pk': self.pk`})

class Ingredient(models.Model):
    recipe=models.ForeignKey(Recipe, on_delete=models.CASCADE)
    ingredient=models.CharField(max_length=100)

    class Meta:
        ordering = ['ingredient']

    def __str__(self):
        return self.ingredient

我想要做的是有一个详细视图,我可以在其中访问食谱属性,如名称和描述,以及能够循环浏览配料。这是我迄今为止的工作:

在views.py中

def recipe_detail_view(request, pk):
    recipe = get_object_or_404(Recipe, pk=pk)
    context = {
        'recipe': recipe,
        'ingredients': Ingredient.objects.filter(recipe=pk)
        }
    return render(request, 'recipes/recipe_detail.html', context=context)

在 urls.py 中

# ...
path('recipes/<str:pk>', views.recipe_detail_view, name='recipe-detail')
# ...

在模板中

<h1 class="title is-1">{{ recipe.name }}</h1>
<p>{{ recipe.description }}</p>
<h3 class="title">Ingredients</h3>
{% for ingredient in ingredients %}
    <h4 class="">{{ ingredient.ingredient.title }}</h3>
{% endfor %}

我想知道如何将其转换为基于类的视图。更具体地说,我想知道如何访问主键并将其传递给过滤器,如下所示:

class RecipeDetailView(generic.DetailView):
    model = Recipe
    template_name = 'recipes/recipe_detail.html'
    context_object_name='recipe'
    extra_context = {
        'ingredients': Ingredient.objects.filter(recipe=pk),
    }

谁能帮忙?

【问题讨论】:

    标签: python python-3.x django django-views


    【解决方案1】:

    您可以使用get_context_data 和get_object 来获取您想要的数据到您的模板。

    class RecipeDetailView(generic.DetailView):
        model = Recipe
        template_name = 'recipes/recipe_detail.html'
        context_object_name='recipe'
    
        def get_context_data(self, **kwargs)
            ctx = super().get_context_data(**kwargs)
            ctx['ingredients'] = Ingredient.objects.filter(recipe=self.get_object().pk)
            return ctx
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-20
      • 2013-09-23
      • 2021-06-28
      • 2014-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-22
      相关资源
      最近更新 更多