pythondjangodjango-modelsdjango-mpttmptt

Django mptt, can I delete the default 'name' filed?


I'm following the django-mptt tutorial,and there is a 'name' filed:

class Genre(MPTTModel):
    name = models.CharField(max_length=50, unique=True)
    parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children')

    class MPTTMeta:
        order_insertion_by = ['name']

compare to my own model:

class Comment(MPTTModel):
    """
    评论表
    """
    name = models.CharField(max_length=1500, unique=True,)
    nid = models.AutoField(primary_key=True)
    news = models.ForeignKey(verbose_name='评论文章', to='News',to_field='id',on_delete=models.CASCADE)
    user = models.ForeignKey(verbose_name='评论者', to='User',to_field='id',on_delete=models.CASCADE)
    content = models.CharField(verbose_name='评论内容', max_length=255)
    create_time = models.DateTimeField(verbose_name='创建时间', auto_now_add=True)
    parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children')

    class MPTTMeta:
        order_insertion_by = ['name']

This 'name' filed is really bothers me, since each time I need to add this filed.

My question is can I hidden or ignore this filed?


Solution

  • The reason that you got an error when you removed the name field is because the order_insertion_by option [readthedocs.io] was referring to that field. But you can let it refer to another field. As the documentation says:

    order_insertion_by

    A list of field names which should define ordering when new tree nodes are being inserted or existing nodes are being reparented, with the most significant ordering field name first. Defaults to [].

    It is assumed that any field identified as defining ordering will never be NULL in the database.

    You can thus for example make use of the primary key instead:

    class Genre(MPTTModel):
        parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children')
    
        class MPTTMeta:
            order_insertion_by = ['pk']