如何通过DateTimeField订购django-mptt树? [英] How to order django-mptt tree by DateTimeField?

查看:118
本文介绍了如何通过DateTimeField订购django-mptt树?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我正在使用的模型:

This is the model I am using:

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']

但是,当我尝试从管理站点添加评论时,会得到:

However, when I try to add a comment from the admin site I get:

ValueError at /admin/app/comment/add/
Cannot use None as a query value

我的模型做错了吗?我觉得django-mptt试图在DateTimeField仍为"None"时获取它,然后再将其设置为数据库级别.

Am I doing something wrong with my model? I feel like django-mptt is trying to get the DateTimeField while it is still "None", before it has been set at the db level.

推荐答案

不,您没有做错任何事情.这是django-mptt中的错误.

No, you're not doing something wrong. This is a bug in django-mptt.

基本上,具有auto_add_now=True的日期时间字段直到django-mptt试图找出将模型插入树中的位置后才得到值.

Basically datetime fields with auto_add_now=True don't get a value until after django-mptt tries to figure out where to insert your model in the tree.

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

I've just created an issue on django-mptt to fix this: https://github.com/django-mptt/django-mptt/issues/175

同时,您可以通过主动设置值来解决此问题.摆脱auto_now_add=True,并在模型上的覆盖save()方法中设置值:

In the meantime, you can work around this by proactively setting the value yourself. Get rid of the auto_now_add=True, and set the value in an overridden save() method on your model::

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)

这篇关于如何通过DateTimeField订购django-mptt树?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆