[Django]-How to bulk_create using a django-mptt model?

3👍

Late reply but it’s not wrong to hardcode lft, rght, and tree_id. It’s what’s actually recommended when adding MPTTModel classes after the model is created, as long as you run rebuild after creation.

for parent in category_parents:
    category_groups = CategoryGroup.objects.filter(category_id=parent.tcgplayer_category_id)
    category_models.extend([
        Category(
            tcgplayer_category_id=model['id'],
            name=model['name'],
            parent=parent,
            lft=0,
            rght=0,
            tree_id=0
        )
        for model in category_groups.values('id', 'name')
    ])
Category.objects.bulk_create(category_models)
Category.objects.rebuild()

You might need to tweak the model a little bit to add some kind of ordering though

from mptt.models import MPTTModel, TreeForeignKey

class Category(MPTTModel):
    parent = TreeForeignKey('self', on_delete=models.CASCADE, blank=True,
        null=True, related_name='children',
    )
    name = models.CharField(max_length=255)
    tcgplayer_category = models.ForeignKey('tcgplayer.TcgCategory', on_delete=models.PROTECT,
        blank=True, null=True)

    class Meta:
        unique_together = (
            ('parent', 'name'),
        )

    def __str__(self):
        return self.name

    class MPTTMeta:
        order_insertion_by = ['name']

Leave a comment