Django自然键不适用于灯具?

时间:2014-07-08 22:22:45

标签: python django serialization fixtures natural-key

我在Django中遇到了固定装置/自然键问题。我想我已解决了大多数常见问题,例如this answer中指定的问题。

这可能都是一个红色的鲱鱼,因为get_by_natural_key在shell中运行得很好:

>>> artifact = Artifact.objects.get_by_natural_key('PP_0772')
>>> artifact
<Artifact: PP_0772: Test Artifact>

我对夹具做错了什么?

Django 1.6

models.py

... 

class ArtifactManager(models.Manager):
    def get_by_natural_key(self, code_number_):
        return self.get(code_number=code_number_)

class Artifact(models.Model):
    def __unicode__(self):
        return self.code_number + ": " + self.title
    def natural_key(self):
        return (self.code_number,)
    objects = ArtifactManager()

    title = models.CharField(max_length = 100, default = 'Untitled')
    code_number = models.CharField('Code Number',
        max_length = 10, unique = True)

class Picture(models.Model):
    def __unicode__(self):
        return self.artifact.code_number + ": " + self.title
    def get_file_name(self):
        return basename(self.image.name)
    def upload_path(instance, image_name):
        output = settings.MEDIA_ROOT + '/uploads/' + image_name
        return output

    image = models.ImageField(upload_to = upload_path, max_length=100,
        blank=False, null=False)
    artifact = models.ForeignKey('Artifact', blank=False, null=False)
    title = models.CharField(max_length = 100, default = 'Primary',
        blank=True, null=True)

... 

我的灯具:pictures.yaml

- pk: 1
  model: collection.picture
  fields: 
    image: /Users/me/images/image.jpg
    artifact: PP_0772
    title: A great image
- pk: 2
  model: collection.picture
  fields: 
    image: /Users/me/images/another_image.jpg
    artifact: PP_0775
    title: A terrific image

...

错误

所以,当我运行./manage.py loaddata pictures时,我得到:

DeserializationError: Problem installing fixture 'pictures.yaml':
[u"'PP_0772' value must be an integer."]

1 个答案:

答案 0 :(得分:1)

事实证明问题出在我的灯具上。我想,自然键需要以列表形式存在;当它说u"'PP_0772' value must be an integer."时,它有点用词不当。也许这指的是列表位置。

所以,它应该是这样的:

- pk: 1
  model: collection.picture
  fields: 
    image: /Users/me/images/image.jpg
    artifact:
      - PP_0772
    title: A great image
- pk: 2
  model: collection.picture
  fields: 
    image: /Users/me/images/another_image.jpg
    artifact:
      - PP_0775
    title: A terrific image
...

希望这有助于处于类似困境的人。