夹具的Django自然键给出反序列化错误

时间:2012-09-25 06:39:59

标签: python django yaml fixtures natural-key

我在SO上看到了一些类似的问题,但似乎没有人回答我的特殊问题。我是Django的新手,并在this page的指导下指导我自己使用自然键加载灯具。然而,我得到反序列化错误,因为Django想要一个外键的整数,并且似乎无法将我的自然键映射到整数主键,如说明中所述。具体来说,我的相关模型代码是:

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)

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)

class LineManager(models.Manager):
    def get_by_natural_key(self, name):
        return self.get(name=name)
class Line(models.Model):
    name = models.CharField(max_length=200, unique=True)

class GraphToLineManager(models.Manager):
    def get_by_natural_key(self, line, graph):
        return self.get(line=line,graph=graph)
class GraphToLine(models.Model):
    line = models.ForeignKey(Line)
    graph = models.ForeignKey(Graph)
    class Meta:
        unique_together = (('line', "graph"),)

我的YAML夹具是:

- model: graphs_container.GraphType
  pk: null
  fields:
    type: TimeSeries
- model: graphs_container.Graph
  pk: null
  fields:
    name: LikesOverTime
    type: [TimeSeries]
- model: graphs_container.Graph
  pk: null
  fields:
    name: UsersOverTime
    type: [TimeSeries]
- model: graphs_container.Line
  pk: null
  fields:
    name: NumUsers
- model: graphs_container.Line
  pk: null
  fields:
    name: NumLikes

但是在尝试运行python manage.py loaddata sample_data.yaml时,我收到以下错误:

DeserializationError: [u"'['TimeSeries']' value must be an integer."]

我做错了什么?

1 个答案:

答案 0 :(得分:5)

你需要

  • 在模型中定义natural_key方法
  • 拥有get_by_natural_key方法
  • 的经理
  • 实际上附加了经理(objects=GraphManager()

在使用您的代码后,我让它成功了:

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()

转储数据:

$ 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)