繁体   English   中英

如何在ForeignKey字段中使用Django中自动创建的隐式直通模型类?

[英]How can I use the automatically created implicit through model class in Django in a ForeignKey field?

在Django我有以下模型。

在Supervisor模型中,我有一个多对多字段,没有明确定义的直通表。 在Topic模型的ForeignKey字段中,我想引用自动创建的中间模型(由Supervisor模型中的多对多字段创建),但我不知道中间模型的名称是什么(因此我在那里写了“???”而不是名字。

Django文档告诉“如果你没有指定显式直通模型,你仍然可以使用隐式直通模型类来直接访问为保持关联而创建的表。”

如何在ForeignKey字段中使用Django中自动创建的隐式直通模型类?

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模型中明确引用它,您可以直接将其声明为模型。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM