这对我有用:
class Task(models.Model):
many_dateranges = models.ManyToManyField('DateRange')
class DateRange(models.Model):
start_date = models.DateTimeField()
end_date = models.DateTimeField()
task_myset = models.ManyToManyField(Task, through=Task.many_dateranges.through)
出于某些原因,我希望在代码中有一个明确的反向关系,而且还可以。
但是,如果是循环导入,则无法用于字符串模型参考:
class DateRange(models.Model):
start_date = models.DateTimeField()
end_date = models.DateTimeField()
task_myset = models.ManyToManyField('myapp.Task', through='myapp.Task.many_dateranges.through', blank=True)
class Task(models.Model):
many_dateranges = models.ManyToManyField(DateRange)
即使没有指定应用名称,我也会收到此错误:
ValueError: Invalid model reference 'myapp.Task.many_dateranges.through'. String model references must be of the form 'app_label.ModelName'.
答案 0 :(得分:0)
好的,只需要输入中间模型名称,这里myapp.Task_many_dateranges
class DateRange(models.Model):
start_date = models.DateTimeField()
end_date = models.DateTimeField()
task_myset = models.ManyToManyField('myapp.Task', through='myapp.Task_many_dateranges', blank=True)
class Task(models.Model):
many_dateranges = models.ManyToManyField(DateRange)
您现在可以在中间模型名称上打印字段的through属性:
instance = Task.objects.first()
print(instance.many_dateranges.through)
# <class 'myapp.models.Task_many_dateranges'>