How to order django-mptt tree by DateTimeField?

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

Am I something wrong with my model? I feel that django-mptt is trying to get a DateTimeField while it is still “None” before it is set to db level.

+5
source share
1 answer

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

Basically, datetime c fields auto_add_now=Truedon't get values ​​until django-mptt tries to figure out where to insert your model into the tree.

I just created a problem on django-mptt to fix this: https://github.com/django-mptt/django-mptt/issues/175

, . auto_now_add=True overridden 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)
+8

All Articles