1

I practice django-mptt and face problem

Here is my models.py

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

I create some data :

  • USA
    • NY
      • BuildingA
        • 3F
        • 4F
      • BuildingB

And now,I need to create 4F under BuildingB

floor3 = Genre.objects.create(name="3F", parent= buildingB)

but face problem :

IntegrityError: duplicate key value violates unique constraint "myapp_genre_name_key"
DETAIL:  Key (name)=(3F) already exists.  

How can I fix it??

Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129
user2492364
  • 6,543
  • 22
  • 77
  • 147
  • Do you really need the `unique=True` argument? It's the key of your problem. – Alex Morozov Feb 02 '16 at 14:11
  • Thank god, your are right !! I originally thought it was because the ````MPTTMeta````:````order_insertion_by = ['name']````. Do you know what is ````order_insertion_by = ['name']```` – user2492364 Feb 02 '16 at 14:13
  • It's a default ordering for newly inserted items. If you order them by hand, this option will no be of great help to you. – Alex Morozov Feb 02 '16 at 14:15

1 Answers1

0

In my understanding, you want your names to be unique across the building. To achieve that, remove the unique=True from the name field declaration and add a Meta option:

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

    class Meta:
        unique_together = (('name', 'parent', ), )
Alex Morozov
  • 5,823
  • 24
  • 28