python - 覆盖保存方法迫使我在管理中保存两次

标签 python django django-models

正在使用 Django1.8.4

所以,我得到了这些模型:

class Occurences(models.Model):
    datetime = models.DateTimeField()

class Serie(models.Model):
    first_occurence = models.DateTimeField(null=True, blank=True)
    last_occurence = models.DateTimeField(null=True, blank=True)
    occurences = models.ManyToManyField(Occurence, null=True, blank=True)
    def save(self, *args, **kwargs):
        super(Series, self).save(*args, **kwargs)
        self.first_occurence = self.occurences.order_by['-datetime'].first()
        self.last_occurence = self.occurences.order_by['datetime'].last()
        super(Series, self).save(*args, **kwargs)

在manage.py shell 上工作得很好。

但是我一使用管理界面进行修改,就不能直接使用了。我必须修改事件字段,保存它,然后重新加载它以在最后再次重新保存......

我已经尝试在 save 函数的开头以及它的开头和结尾(两次)执行 super(...).save(...) ,以及在最后。

我的目标是能够按第一个出现(或最后一个出现,但一个就足够了)进行排序。

Serie.objects.order_by('first_occurence__datetime')

因为这不起作用

Serie.objects.order_by('occurence__first')
Serie.objects.order_by('occurence__first__datetime')
Serie.objects.order_by('occurence__set__first')

我就是不明白:/

最佳答案

由于 Django ORM,这些对 first_occurrencelast_occurrence 的显式引用实际上是不必要的。它们提供的所有功能都可以通过 ManyToMany 字段occurrences隐式使用。

如果您向 Occurences 模型添加 Meta.ordering 属性,则可以查询第一个和最后一个。例如:

class Occurence(models.Model):
    datetime = models.DateTimeField()

    class Meta:
        ordering = ('datetime',)

class Series(models.Model):
    first_occurence = models.DateTimeField(null=True, blank=True)
    last_occurence = models.DateTimeField(null=True, blank=True)
    occurences = models.ManyToManyField(Occurence, null=True, blank=True)


my_series = Series.objects.get(...)
first = my_series.objects.earliest()
latest = my_series.objects.latest()

此外,鉴于上述情况,您可以按出现次数进行排序,以查看哪些出现是最新(或最早)的。例如:

series_with_latest_occurences = Series.objects.order_by('-occurences__datetime')
series_with_earliest_occurences = Series.objects.order_by('occurences__datetime')

关于python - 覆盖保存方法迫使我在管理中保存两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33373513/

相关文章:

python - Mongoengine-类型错误: Instantiating a document with positional arguments is not supported

python - 将列表列表的数据从字符串格式转换为列表

python - 将超时键添加到 Chalice config.json 后 Lambda 超时值未更改

python - Django 相当于 COUNT 和 GROUP BY

python - 在 Django/MySQL 中创建单例表的最佳方法

django - 如何从带注释的 Django 查询中过滤/排除非事件评论?

python - 在 tkinter 中显示 Pandas 数据框

django - Django过滤查询外键

django - 应用程序名称附加到 Django 中的表名

django - 在 Django 中指定列名的别名