首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在django的detail视图中使用外键将模型中的项目连接到另一个模型?

如何在django的detail视图中使用外键将模型中的项目连接到另一个模型?
EN

Stack Overflow用户
提问于 2021-01-18 19:22:31
回答 1查看 29关注 0票数 0

我正在尝试创建一个卡通流媒体网站,当用户点击他们选择的卡通(例如:精灵宝可梦)时,他们可以看到作为列表的季节以及卡通的细节。

代码语言:javascript
运行
复制
from django.db import models

class Cartoon(models.Model):
    name = models.CharField(max_length=200)
    cover = models.ImageField()
    description = models.TextField()
    start_date = models.CharField(max_length=50)
    end_date = models.CharField(max_length=50)
    
    def __str__(self):
        return self.name 


class CartoonSeason(models.Model):
    cartoon = models.ForeignKey(Cartoon, null=True, on_delete=models.SET_NULL)
    number = models.IntegerField()
    season_cover = models.ImageField(blank=True, null=False)
    season_name = models.CharField(max_length=200, blank=True, null=True)
    season_description = models.TextField(blank=True, null=False)

在这里,我使用外键将卡通模型与CartoonSeason模型相链接,因此当要添加新赛季时,它会自动与相应的卡通相链接

代码语言:javascript
运行
复制
from django.shortcuts import render
from django.http import HttpResponse
from  django.views.generic import ListView, DetailView
from .models import CartoonSeason, Cartoon

class CartoonListView(ListView):
    model = Cartoon
    template_name = "index.html"


class CartoonSeasonView(DetailView):
    queryset = CartoonSeason.objects.filter()
    model = CartoonSeason
    template_name = "season.html"

我使用详细信息视图来显示CartoonSeason模型,以便它也显示卡通的详细信息,但是当我尝试加载季节时,它只显示主键为1的季节。我希望它显示添加到卡通中的所有季节。这是我的seasons.html

代码语言:javascript
运行
复制
{% extends 'base.html' %}
{% block title %}
    test
{% endblock %}
{% block content %}
    <main>
        <section class="cartoon-description">
            <div class="season_head">
                <img src="{{object.cartoon.cover.url}}" width="260px" alt="">
                <div class="cartoon-name">
                    <h1>{{object.cartoon.name}}</h1>
                    <small >{{object.cartoon.start_date}} - {{object.cartoon.end_date}}</small>
                    <br>
                    <div class="description">
                        <strong>Description:</strong>
                        <br>
                        <p>{{object.cartoon.description}}</p>
                    </div>
                </div>
                
            </div>
        </section>
        <hr>
    </main>
{% endblock %}

这是我的urls.py

代码语言:javascript
运行
复制
from .views import CartoonListView, CartoonSeasonView


urlpatterns = [
    path('', CartoonListView.as_view(), name="home"),
    
    path('cartoon/<int:pk>' , CartoonSeasonView.as_view(), name="cartoon"),
    
 
]

这是我的主模板

代码语言:javascript
运行
复制
{% extends 'base.html'%}

{% block title %}
    Home - CartoonsPalace
{% endblock %}
{% block content %}

<main>
    <section class="cartoon-list">
        <div class="select-text">
            <h1>Pick Your Cartoon Series of Choice:-</h1>
        </div>
        {% for cartoon in object_list %}
        <div class="list">
            <a href="{% url 'cartoon' cartoon.pk %}"><div class="list-object">
                
                <img src="{{cartoon.cover.url}}" alt="" width="184px">
                <h3>{{cartoon.name}}</h3>
                <span>{{cartoon.start_date}} - {{cartoon.end_date}}</span>
            </div>
        </a>
        </div>
        {% endfor %}
    </section>
</main>



{% endblock %}

任何帮助都将不胜感激。

EN

回答 1

Stack Overflow用户

发布于 2021-01-18 20:04:14

好的,当你想通过外键访问与另一个对象相关的所有对象时,你有两个简单的选择:1.使用卡通设置查询(反向关系):

代码语言:javascript
运行
复制
cartoon = Cartoon.objects.get(id = 'pk') # get the pk by passing in url
cartoon_season = cartoon.cartoonseason_set.all()
# object.(name of model CartoonSeason must be in lowercase )._set.all()

或使用CartoonSeason设置查询(推荐):

代码语言:javascript
运行
复制
#before this you must have the id of the cartoon :
cartoon = Cartoon.objects.get(id = pk)
seasons = CartoonSeason.objects.filter(cartoon = cartoon)

我不知道你的卡通模板或url,但我假设在你的卡通模板中,你有一个链接到卡通的季节细节,所以你应该在那里传递卡通的id:{{cartoon.id}},在你的url中,你可以在你的季节细节中使用这个id :但请注意,当你使用DetailView并想使用通过url传递的id时,你应该定义一个这样的get_queryset

代码语言:javascript
运行
复制
class CartoonSeasonView(DetailView):
    model = CartoonSeason
    template_name = "season.html"
    def get_queryset(self, *args, **kwargs):
        #before this you must have the id of the cartoon :
        cartoon = Cartoon.objects.get(id = self.kwargs['pk'])
        seasons = CartoonSeason.objects.filter(cartoon = cartoon)

请记住,用户不再需要拥有query_set。这样你就可以在动画季页面上显示动画片的名字或者海报了。记住,我们的user detail视图为了只显示一个对象的细节,而不是7(像卡通的季节),.You可以使用ListView,或者如果你想在一个模板中显示不同的数据,可以使用TemplateView。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65773585

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档