简体   繁体   中英

Django Many-to-Many query all() returns empty set

As per the Django docs I created a relationship between people and dates for a museum application.

First the models (with unnecessary fields removed):

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)
    . . . .

Then the test:

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")

Now the following queries return the expected sets:

AgentDateType.objects.all()
c_life.date_for_agent.all()
c_act.date_for_agent.all()

However, caesar.dates.all() , which should be the most straightforward, returns an empty set. What gives?

Django's ManyToManyField takes positional arguments which are not in the order you've provided. See the source for M2M . I suggest you use keyword arguments, as positional arguments can cause problem let alone even change between minor versions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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