如何在Django的ForeignKey字段中使用通过模型类自动创建的隐式?
问题内容:
在Django中,我有以下模型。
在Supervisor模型中,我有一个多对多字段,没有显式定义的直通表。在主题模型的ForeignKey字段中,我想引用自动创建的中间模型(由Supervisor模型中的多对多字段创建),但是我不知道中间模型的名称是什么(因此我在此处写了“
???”,而不是名称)。
Django文档告诉我们:“如果不指定显式的直通模型,则仍然可以使用隐式的直通模型类直接访问为保存关联而创建的表。”
如何在Django的ForeignKey字段中使用通过模型类自动创建的隐式?
import re
from django.db import models
class TopicGroup(models.Model):
title = models.CharField(max_length=500, unique='True')
def __unicode__(self):
return re.sub(r'^(.{75}).*$', '\g<1>...', self.title)
class Meta:
ordering = ['title']
class Supervisor(models.Model):
name = models.CharField(max_length=100)
neptun_code = models.CharField(max_length=6)
max_student = models.IntegerField()
topicgroups = models.ManyToManyField(TopicGroup, blank=True, null=True)
def __unicode__(self):
return u'%s (%s)' % (self.name, self.neptun_code)
class Meta:
ordering = ['name']
unique_together = ('name', 'neptun_code')
class Topic(models.Model):
title = models.CharField(max_length=500, unique='True')
foreign_lang_requirements = models.CharField(max_length=500, blank=True)
note = models.CharField(max_length=500, blank=True)
supervisor_topicgroup = models.ForeignKey(???, blank=True, null=True)
def __unicode__(self):
return u'%s --- %s' % (self.supervisor_topicgroup, re.sub(r'^(.{75}).*$', '\g<1>...', self.title))
class Meta:
ordering = ['supervisor_topicgroup', 'title']
问题答案:
它只是被称为through
-因此您的情况是Supervisor.topicgroups.through
。
尽管我认为如果要在Topic模型中显式引用它,则最好将其直接声明为模型。