Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

In Django I have the following models.

In the Supervisor model I have a many-to-many field without an explicitly defined through table. In the ForeignKey field of the Topic model I would like to refer to the automatically created intermediate model (created by the many-to-many field in the Supervisor model), but I don't know what is the name of the intermediate model (therefore I wrote '???' there, instead of the name).

Django documentation tells that "If you don’t specify an explicit through model, there is still an implicit through model class you can use to directly access the table created to hold the association."

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

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']
like image 482
sgd Avatar asked Jul 10 '14 21:07

sgd


1 Answers

It's just called through - so in your case, Supervisor.topicgroups.through.

Although I think that if you're going to be referring to it explicitly in your Topic model, you might as well declare it directly as a model.

like image 55
Daniel Roseman Avatar answered Sep 22 '22 02:09

Daniel Roseman