Django Natural Key for Fixtures Give Deserialization Error

前端 未结 1 2007
慢半拍i
慢半拍i 2021-01-14 15:53

I\'ve seen a few similar questions to this on SO, but none seem to answer my particular problem. I\'m new to Django and was guiding myself by the instructions at this page t

相关标签:
1条回答
  • 2021-01-14 16:34

    You need to

    • define natural_key method in your models
    • have a manager with get_by_natural_key method
    • actually attach the managers (objects=GraphManager())

    After playing with your code, I made it work:

    class GraphTypeManager(models.Manager):
        def get_by_natural_key(self, type):
            return self.get(type=type)
    
    class GraphType(models.Model):
        type = models.CharField(max_length=100, unique=True)
        objects = GraphTypeManager()
    
        def natural_key(self):
            return (self.type,)  # must return a tuple
    
    class GraphManager(models.Manager):
        def get_by_natural_key(self, name):
            return self.get(name=name)
    
    class Graph(models.Model):
        name = models.CharField(max_length=200, unique=True)
        type = models.ForeignKey(GraphType)
        objects = GraphManager()
    

    Dumping the data:

    $ bin/django dumpdata index --indent=4 --natural > project/apps/fixtures_dev/initial_data.json
    [
        {
            "pk": 1,
            "model": "index.graphtype",
            "fields": {
                "type": "asotuh"
            }
        },
        {
            "pk": 1,
            "model": "index.graph",
            "fields": {
                "type": [
                    "asotuh"
                ],
                "name": "saoneuht"
            }
        }
    ]
    
    bin/django loaddata project/apps/fixtures_dev/initial_data.json 
    Installed 2 object(s) from 1 fixture(s)
    
    0 讨论(0)
提交回复
热议问题