强制性的,我是一个django初学者,我不明白为什么我的代码不工作。如何检查对象在模板中的哪个子类?
我想通过视图中的父类进行排序以获取对象,然后将该对象传递给模板。在该模板中,我为每个子类显示了某些字段,还有一些字段是从父类继承的。
我试过在我的模板中使用isinstance()
,但它引发了错误。之后,我尝试通过我的模板中的if语句来检查每个子类的静态属性。当这样做时,没有任何子类特定字段显示。所以我试图在视图中设置属性,并且仍然没有显示任何子类特定的字段。
下面是父对象类和子类中的一个(型号):
class Chunk(models.Model):
name = models.CharField(max_length=250)
text = models.CharField(max_length=500)
images = models.FileField()
question = models.CharField(max_length=250)
expected_completion_time = models.IntegerField(default=1)
keywords = models.CharField(max_length=250, blank=True, null=True)
topic = models.CharField(max_length=250, blank=True, null=True)
course = models.CharField(max_length=250, blank=True, null=True)
def get_absolute_url(self):
return reverse('detail', kwargs={'pk':self.pk})
def __str__(self):
return self.name
class Concept(Chunk):
application = models.CharField(max_length=500)
subconcept1 = models.CharField(max_length=500, blank=True, null=True)
subconcept2 = models.CharField(max_length=500, blank=True, null=True)
subconcept3 = models.CharField(max_length=500, blank=True, null=True)
subconcept4 = models.CharField(max_length=500, blank=True, null=True)
subconcept5 = models.CharField(max_length=500, blank=True, null=True)
subconcept6 = models.CharField(max_length=500, blank=True, null=True)
subconcept7 = models.CharField(max_length=500, blank=True, null=True)
subconcept8 = models.CharField(max_length=500, blank=True, null=True)
subconcept9 = models.CharField(max_length=500, blank=True, null=True)
subconcept10 = models.CharField(max_length=500, blank=True, null=True)
conceptimage = models.FileField(blank=True, null=True)
@property
def mode(self):
return "concept"
这里是视图:
def startpomodoro(request):
key = getpriority(Chunk.objects.all())
object = Chunk.objects.get(id=key)
a = random() > 0.5
mode = str()
if isinstance(object, Problem):
if a:
mode = "problemoutline"
else:
mode = "problemfull"
elif isinstance(object, Concept):
mode = "concept"
elif isinstance(object, Formula):
mode = "formula"
elif isinstance(object, Code):
mode = "code"
context = dict(object=object, mode=mode)
return render(request, 'pomodoro/pomodorogo.html', context)
这里是模板的相关部分:
<center>
<p>{{ object.text }}</p>
{% if mode == concept %}
<p>{{ object.application }}</p>
<p>{{ object.subconcept1 }}</p>
{% if object.subconcept2 %}
<p>{{ object.subconcept2 }}</p>
{% elif mode == formula %}
我不明白为什么我没有任何这些方法来工作。我确信这是我执行的一个问题,但我不知道我做错了什么。
但对象不是任何的茨艾伦东西。这是一个大块,因为这就是你要求的。 –
当我创建这些其他东西时,它们被输入到它们各自的数据表和块表中。你是否在说我所做的只能让我访问Chunk表中的信息?如果是这样,你能推荐任何适当的方法从块到其相应的子类数据? – Era
我看到的最简单的解决方案是使用OneToOneField进行继承。 因此,请检查此[链接](https://docs.djangoproject.com/el/1.10/topics/db/examples/one_to_one/) –