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

7 投票
1 回答
1418 浏览
提问于 2025-04-18 12:52

在Django中,我有以下几个模型。

在Supervisor模型里,我有一个多对多的字段,但没有明确指定一个中间表。在Topic模型的外键字段中,我想引用那个自动创建的中间模型(这个模型是由Supervisor模型中的多对多字段生成的),但我不知道这个中间模型的名字(所以我在这里写了'???',而不是名字)。

Django的文档提到:“如果你没有指定一个明确的中间模型,仍然会有一个隐式的中间模型类,你可以用它直接访问用来保存关联关系的表。”

我该如何在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']

1 个回答

11

这个东西叫做 through,所以在你的例子中,就是 Supervisor.topicgroups.through

不过我觉得,如果你打算在你的主题模型中明确提到它,那不如直接把它声明为一个模型。

撰写回答