如何通过DateTimeField对django-mptt树进行排序?

5

这是我正在使用的模型:

class Comment(MPTTModel):
    comment = models.CharField(max_length=1023)
    resource = models.ForeignKey('Resource')
    created_at = models.DateTimeField(auto_now_add=True)
    parent = TreeForeignKey('self', null=True, blank=True, related_name='children')
    author = models.ForeignKey(User)

    class MPTTMeta:
        order_insertion_by = ['created_at']

然而,当我尝试从管理员网站添加评论时,我遇到了以下问题:
ValueError at /admin/app/comment/add/
Cannot use None as a query value

我的模型有什么问题吗?我感觉django-mptt试图在DateTimeField还没有被设置为数据库级别的"None"时获取它。

1个回答

8

不,你没有做错什么。这是django-mptt中的一个错误。

基本上,具有auto_add_now=True的datetime字段在django-mptt尝试找出在树中插入你的模型的位置之前不会得到值。

我刚在django-mptt上创建了一个问题来解决这个问题: https://github.com/django-mptt/django-mptt/issues/175

同时,你可以通过主动设置值来解决这个问题。去掉auto_now_add=True,并在你的模型上覆盖save()方法中设置这个值::

from datetime import datetime

class Comment(MPTTModel):
    comment = models.CharField(max_length=1023)
    resource = models.ForeignKey('Resource')
    created_at = models.DateTimeField()
    parent = TreeForeignKey('self', null=True, blank=True, related_name='children')
    author = models.ForeignKey(User)

    class MPTTMeta:
        order_insertion_by = ['created_at']

    def save(self, *args, **kwargs):
        if not self.created_at:
            self.created_at = datetime.now()
        super(Comment, self).save(*args, **kwargs)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接