Django: Create fixtures without specifying a primary key?

前端 未结 5 2128
梦毁少年i
梦毁少年i 2020-12-07 22:16

One of the things that bugs me about Django fixtures is that you\'ve got to specify every model\'s primary key. Is there any way to create fixtures without having to specify

相关标签:
5条回答
  • 2020-12-07 22:30

    If you check out the manage.py dumpdata command, you will see some options called --natural-foreign, --natural-primary. If you look at the output you can see that the objects are dumped without using primary keys or foreign keys.

    0 讨论(0)
  • 2020-12-07 22:36

    I had to deal with existing DB schema without possibility to change it, so I need a table with complex primary key or without it at all - but not with the serial one. What I did:

    I've specified a primary_key=True to the field, which should not be unique at all and wrote overloaded method:

    class ContraIndicationsMedicines(models.Model):
    
        contra_indication = models.ForeignKey(ContraIndication, primary_key=True)
        medicine = models.ForeignKey(Medicine)
    
        def validate_unique(self, exclude=None): 
            pass
    

    In fact, it worked for my needs, but there are more validations call inside django.contib.admin.* and not all the inlines e.t.c are guaranteed to work. That was the only solution I could implement... ((

    0 讨论(0)
  • 2020-12-07 22:39

    Use "pk: null" instead of "pk: 1" (or whatever), which will result in the PK being set to None, and when the object is saved a primary key will be assigned.

    This works for YAML at least, I'm guessing you're using that if you are creating by hand.

    0 讨论(0)
  • 2020-12-07 22:46

    A friend of mine suggested the fixture module: http://farmdev.com/projects/fixture/

    0 讨论(0)
  • 2020-12-07 22:51

    You should have a look at Natural Keys if you're wiling to add relation without using pk's

    https://docs.djangoproject.com/en/dev/ref/django-admin/#dumpdata-app-label-app-label-app-label-model

    0 讨论(0)
提交回复
热议问题