根据Django docs,我创建了人与博物馆申请日期之间的关系。
首先是模型(删除了不必要的字段):
class Agent(models.Model):
name = models.CharField(max_length=255)
dates = models.ManyToManyField(HistoricDate, 'date_for_agent', models.CASCADE, through='AgentDateType')
. . . .
class HistoricDate(models.Model):
display = models.CharField(max_length=255, help_text='Textual representation of date')
earliest = models.CharField(max_length=15, blank=True)
earliest_accuracy = models.BooleanField(default=False, verbose_name="circa")
latest = models.CharField(max_length=15, blank=True)
latest_accuracy = models.BooleanField(default=False, verbose_name="circa")
class AgentDateType(models.Model):
datation = models.ForeignKey(HistoricDate, models.PROTECT)
dated = models.ForeignKey(Agent, models.CASCADE)
date_type = models.CharField(max_length=31, choices=date_types)
. . . .
然后测试:
caesar = Agent.objects.create(name="Gaius Julius Caesar", name_type="personal", culture="Ancient Rome", display="Julius Caesar (Roman, 100–44 B.C.)")
c_life = HistoricDate.objects.create(display="13 July 100–15 March 44 B.C.", earliest="-100-07-13", earliest_accuracy=False, latest="-44-03-15", latest_accuracy=False)
c_act = HistoricDate.objects.create(display="60–44 B.C.", earliest="-60", earliest_accuracy=False, latest="-44-03-15", latest_accuracy=False)
caesar_lives = AgentDateType.objects.create(dated=caesar, datation=c_life, source="Suetonius, Lives of the Caesars", date_type="life")
caesar_acts = AgentDateType.objects.create(dated=caesar, datation=c_act, source="Livy", date_type="activity")
现在,以下查询返回预期的集合:
AgentDateType.objects.all()
c_life.date_for_agent.all()
c_act.date_for_agent.all()
但是,caesar.dates.all()
应该是最简单的,返回一个空集。是什么给了什么?
答案 0 :(得分:1)
Django' ManyToManyField
采取不符合您提供的顺序的位置参数。请参阅source for M2M。我建议你使用关键字参数,因为位置参数可能导致问题,更不用说在次要版本之间进行更改。