假设我们有2个应用程序,游戏和流媒体。两个应用程序都有自己的视图,模型,模板等。在应用程序流媒体中,我们得到了模型Streamer
与领域
games = models.ManyToManyField('games.Game')
我们正在从应用游戏中导入模型游戏。现在,在迁移之后,添加一些内容我们可以创建对象Streamer并为他分配正在播放的游戏。但是,当显示所有选择Streamer的游戏时,通过添加模板标签来播放
{{ streamer.games }}
我们正在上模板字符串
games.Game.None
所以有些东西会导致它,我们还不知道到底是什么。我们为游戏,流媒体,模板,网址创建了一些视图,因为我们获得了流媒体的昵称或者流媒体到YouTube / Twitch等链接的数据,但是如果我们想要在我们的应用程序中使用流媒体可以显示分配给流媒体的游戏我们应该从彩带和游戏中导入视图和模型吗?或者我们应该更改应用程序的流媒体/ views.py任何视图,并在那里放置从应用游戏导入的游戏?我知道如何使用模型和关系ManyToMany在单个应用程序中执行此操作,因为我已经有机会(使用StackOverFlow帮助)执行此类操作。但是知道我正在做项目(用于学习),我已经决定更好地分离单个应用程序,我不知道如何做到这一点。如果两个模型都在1个应用程序中并且将编写视图,我可以使用这样的样子
{% for game in streamer.games.all %}
{{ games.title }}
{% endfor %}
但这对我来说是个问题,因为那些是两个不同的应用程序(我正在阅读,分离它们真的更好,就像好的一样)
幡/ models.py
from django.db import models
from games.models import Game, Genre
from shots.utils import get_unique_slug
from django.utils import timezone
...
# model for streamer
class Streamer(models.Model):
nick = models.CharField(max_length=30)
twitch = models.CharField(max_length=70)
games = models.ManyToManyField('games.Game')
...
幡/ views.py
from django.shortcuts import render, get_object_or_404, redirect
from .models import Streamer
from django.utils import timezone
from django.contrib.auth.decorators import login_required
from .forms import StreamerForm
...
# defining page for single streamer
def streamer_detail(request, slug):
streamer = get_object_or_404(Streamer, slug=slug)
return render(request, 'streamers/streamer_detail.html', {'streamer': streamer})
...
幡/模板/ streamer_detail.html
{% block content %}
<div class="post">
{% if streamer.published_date %}
<div class="date">
{{ streamer.published_date }}
</div>
{% endif %}
{% if user.is_authenticated %}
<a href="{% url 'streamer_edit' slug=streamer.slug %}">Edit streamer</a>
{% endif %}
<h2>{{ streamer.nick }}</h2>
<a href="https://{{streamer.youtube}}">My YouTube Channel</a>
<a href="https://{{ streamer.twitch }}">My Twitch Channel</a>
<p>I'm streaming on {{ streamer.platform }}</p>
Games that I'm playing
{{ streamer.games }}
</div>
{% endblock %}
游戏/ models.py
from django.db import models
from django.utils import timezone
from shots.utils import get_unique_slug
# model for game
class Game(models.Model):
title = models.CharField(max_length=70)
genres = models.ManyToManyField('Genre', blank=True)
...
# model for genre
...
游戏/ views.py
from django.shortcuts import render, get_object_or_404, redirect
from .models import Game
from django.utils import timezone
from django.contrib.auth.decorators import login_required
from .forms import GameForm
# defining page with newest games
...
# defining page for single games
def game_detail(request, slug):
game = get_object_or_404(Game, slug=slug)
return render(request, 'games/game.html', {'game': game})
...
好吧,看起来我们不需要从1个应用程序的视图导入任何东西到第2个应用程序的视图。要访问这些查询集,我们需要的是使用正确的循环,在我的情况下,有1个字母太多
games.title
所以当我把它改成game.title时一切正常
{% for game in streamer.games.all %}
{{ game.title }}
{% endfor %}