2012-03-07 14 views
5

Jest to model Używam:Jak zamówić drzewo django-mptt przez DateTimeField?

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

Jednak gdy próbuję dodać komentarz ze strony administratora uzyskać:

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

robię coś złego w moim modelu? Czuję, że django-mptt próbuje uzyskać atrybut DateTimeField, gdy wciąż jest "None", zanim zostanie ustawiony na poziomie db.

Odpowiedz

8

Nie, nie robisz czegoś złego. To jest błąd w django-mptt.

Zasadniczo pola datetime z auto_add_now=True nie otrzymują wartości dopóki django-mptt nie spróbuje ustalić, gdzie wstawić model do drzewa.

Właśnie stworzył problem w Django mptt aby rozwiązać ten problem: https://github.com/django-mptt/django-mptt/issues/175

W międzyczasie, można to obejść poprzez aktywne ustawienie wartości samodzielnie. Pozbądź się auto_now_add=True i ustaw wartość w nadpisanej metodzie zapisywania() w swoim modelu:

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) 
Powiązane problemy