【问题标题】:How do I access the linked table in django如何访问 django 中的链接表
【发布时间】:2021-12-22 18:19:47
【问题描述】:

我的博客在每篇博文中都有多个食谱。而且这些食谱在所有博客文章中都多次使用。

我正在尝试创建一个可以在网格中显示所有食谱的页面。一旦访问者点击一个食谱,我希望它链接到数据库中包含该特定食谱的第一篇博客文章。因为我的每篇博文都有 html 页面,但不是每个食谱都有。

我无法想象这将如何构建和完成。我应该重新设计模型还是有办法使用 django 模板来做到这一点?任何帮助将不胜感激!

models.py

class Posts(models.Model):
    title = models.CharField(max_length=155)
    summary = models.TextField(blank=True, null=True)
    slug = models.SlugField(unique=True, max_length=155)
    

class PostRecipes(models.Model):
    post = models.ForeignKey('Posts', models.DO_NOTHING)
    recipe = models.ForeignKey('Recipes', models.DO_NOTHING)


class Recipes(models.Model):
    title = models.CharField(max_length=155)
    summary = models.TextField(blank=True, null=True)
    content = models.TextField(blank=True, null=True)

views.py

def allrecipes(request):
    recipes = Recipes.objects.all()

    context = {
        'recipes': recipes,
    }
    return render(request, "All-recipes.html", context)

All-recipes.html

{% for item in recipes %}
  <a href="{{ STATIC_URL }}/{{ item.slug }}">{{ item.title }}</a>
{% endfor %}

【问题讨论】:

    标签: django django-models django-views django-templates django-orm


    【解决方案1】:

    实际上你应该使用ManyToManyField

    class Posts(models.Model):
        title = models.CharField(max_length=155)
        summary = models.TextField(blank=True, null=True)
        slug = models.SlugField(unique=True, max_length=155)
        
    
    class Recipes(models.Model):
        title = models.CharField(max_length=155)
        summary = models.TextField(blank=True, null=True)
        content = models.TextField(blank=True, null=True)
        posts = mdoels.ManyToManyField("Posts", related_name='recipes')
    

    Django 文档示例:https://docs.djangoproject.com/en/3.2/topics/db/examples/many_to_many/

    之后,您可以通过以下方式访问相关表:

    Recipes.objects.first().posts # first recipe for example
    Posts.objects.first().recipes # first post for example, accessing via related name
    

    在你的模板中会是这样的:

    {% for item in recipes %}
      <a href="{{ STATIC_URL }}/{{ item.posts.first.slug }}">{{ item.posts.first.title }}</a>
    {% endfor %}
    

    【讨论】:

    • 谢谢阿明。你能告诉我如何使用它在 django 模板中呈现吗?
    • 我已经为你更新了答案@haashe
    猜你喜欢
    • 2021-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多