如何收集与此主键相关的对象

时间:2016-04-25 17:59:37

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

所以我可以在我看来访问这个模型。从这里我也可以访问lolChamp冠军。现在lolChamp有这个infoID,它是它的主键。这个字段是一堆其他表的外键,它包含我想要的信息。但我似乎无法掌握这些信息。我已经尝试过我的HTML了。我从民意调查django教程中得到了这个想法。

{% for spell champBuild.spellSet_set.all %}
    <h1> {{spell.spell_name}} </h1>
{% endfor %}

^什么都不做

class champBuild(models.Model):
    champion = models.ForeignKey(lolChamp, default="-1")
    build_name = models.CharField(max_length=200, primary_key=True, default=time.time())
    build_date = models.DateTimeField('date created')
    items = models.ForeignKey(lolItem, default=0)
    items2 = models.ForeignKey(lolItem, default=0, related_name='item2')
    items3 = models.ForeignKey(lolItem, default=0, related_name='item3')
    items4 = models.ForeignKey(lolItem, default=0, related_name='item4')
    items5 = models.ForeignKey(lolItem, default=0, related_name='item5')
    items6 = models.ForeignKey(lolItem, default=0, related_name='item6')

class lolChamp(models.Model):
    champ_name = models.CharField(max_length=50, unique=True)
    champ_title = models.CharField(max_length=50, unique=True)
    full_img = models.CharField(max_length=50)
    sprite = models.CharField(max_length=50)
    x = models.IntegerField()
    y = models.IntegerField()
    w = models.IntegerField()
    h = models.IntegerField()
    tags = models.TextField()
    infoID = models.IntegerField(primary_key=True)
    def __str__(self):
        return self.champ_name
class spellSet(models.Model):
    champid = models.ForeignKey(lolChamp, on_delete=models.CASCADE, default=0)
    spell_name = models.CharField(max_length=100, primary_key=True)
    full_img = models.CharField(max_length=100)
    def __str__(self):
        return self.spell_name

这是我的views.py

from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.views import generic
from .models import champBuild
from lolBuilds.models import lolItem, skinSet
from .forms import champBuildForm, champBuildUpdateForm
# Create your views here.

class DetailView(generic.DetailView):
    model = champBuild
    template_name = 'lolBuilds/detail.html'

如何获得所有具有lolChamp外键的法术?

1 个答案:

答案 0 :(得分:0)

spells = spellSet.objects.filter(champid=champ.infoID) # champ is an object of lolchamp model

https://docs.djangoproject.com/en/1.9/topics/db/queries/

了解查询集