简体   繁体   English

Django外键关系

[英]Django foreign key relation

I recently started working with Python and Django for making a website, and i've run into a problem that i just cannot figure out. 我最近开始使用Python和Django来制作网站,但遇到了一个我无法解决的问题。

You can be sure, that it's becuase of my utter inexperience, and that i've overlooked something simple or done something dumb, but oh well.. 您可以肯定,这是由于我完全没有经验,而我却忽略了一些简单的事情或做了一些愚蠢的事情,但是哦。

On my site i have a page for displaying details about a recipe (description, ingredients, instructions and such). 在我的网站上,我有一个页面来显示有关食谱的详细信息(说明,成分,说明等)。 I'm displaying this like such: 我正在这样显示:

views.py
class RecipeView(generic.DetailView):
    model = recipe
    template_name = 'whatsfordinner/recipe.html'
    context_object_name = 'details'

So far i've been able to display my single info things, no problem ( {{details.whatever}} ) 到目前为止,我已经能够显示我的单个信息,没问题({{details.whatever}})

My problem is that both instructions and ingredients are stored in my db as a foreign key relation, and as such needs to be outputted differently. 我的问题是指令和成分都作为外键关系存储在我的数据库中,因此需要以不同的方式输出。 My database looks like this: 我的数据库如下所示:

class recipe(models.Model):
    title = models.CharField(max_length=255)
    description = models.TextField(default="No decsription added")
    image = models.ImageField(upload_to='images/',
                                        default='images/default.jpg')
    total_favourites = models.IntegerField()
    servings = models.IntegerField()

    def __str__(self):
        return self.title

class ingredients(models.Model):
    recipe = models.ForeignKey(recipe)
    ingredient = models.CharField(max_length=255)

I'm having a really hard time outputting the relevant ingredients for my selected recipe, and i would love some pointers. 我很难为我选择的食谱输出相关的食材,我很乐意提供一些指导。

For an recipe object, say r : 对于配方对象,说r

r.ingredients_set.all() will list all the ingredients linked to that recipe. r.ingredients_set.all()将列出与该食谱链接的所有成分。

You can further filter on this: r.ingredients_set.filter(title__startswith='clover') 您可以对此进行进一步过滤: r.ingredients_set.filter(title__startswith='clover')

There's a comprehensive guide in Django Documentation: https://docs.djangoproject.com/en/1.9/topics/db/examples/many_to_one/ Django文档中有完整的指南: https : //docs.djangoproject.com/en/1.9/topics/db/examples/many_to_one/

Suppose you want the list of all ingredients for a recipe in your views.py: 假设您想要在您的views.py中列出食谱的所有成分的清单:

ingredient_list = r.ingredients_set.all()

Then pass the ingredient_list in your context dictionary to your template. 然后将上下文字典中的Ingredient_list传递给模板。 If you don't know what context dictionary is, what are you doing man, go through the Django documentation! 如果您不知道上下文字典是什么,那么您在做什么,请阅读Django文档! Lot's of people put in lot of effort to create that nice documentation. 很多人都在花很多精力来创建漂亮的文档。

suppose context['ingredients'] = ingredient_list , where context is the context dictionary you are passing to your template html. 假设context['ingredients'] = ingredient_list ,其中context是您要传递给模板html的上下文字典。 Then in your template, use Django Template Language for something like this: 然后在您的模板中,使用Django模板语言执行以下操作:

{% for i in ingredients %}
  <p>{{ i.ingredient }}</p>
{% endfor %}

Here ingredients is the ingredient_list you passed using the context dictionary, and for each ingredient object i in the for loop, you are displaying the value of <ingredient object i>.ingredient 这里ingredientsingredient_list您使用上下文传递字典,并且对于每个成分对象i在for循环中,正在显示的值<ingredient object i>.ingredient

Here's a link to the official tutorial, if it helps. 如果有帮助,这是官方教程的链接。 https://docs.djangoproject.com/en/1.9/intro/tutorial01/ https://docs.djangoproject.com/zh-CN/1.9/intro/tutorial01/

See here: https://docs.djangoproject.com/en/1.9/topics/class-based-views/generic-display/#adding-extra-context 参见此处: https : //docs.djangoproject.com/zh-CN/1.9/topics/class-based-views/generic-display/#adding-extra-context

class PublisherDetail(DetailView):

    model = Publisher


class RecipeView(generic.DetailView):
    model = recipe
    template_name = 'whatsfordinner/recipe.html'
    context_object_name = 'details'

    def get_context_data(self, **kwargs):
        # Call the base implementation first to get a context
        context = super(RecipeView, self).get_context_data(**kwargs)
        # Add in a QuerySet of all the books
        context['ingredient_list'] = recipe.ingredients_set.all()
        return context

above is untested 以上未经测试

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM