python - 从夹具加载数据时出错

标签 python django

我有以下模型和经理。

class StateManager(models.Manager):
    def get_by_natural_key(self, name):
        return self.get(name=name)


class State(models.Model):

    class Meta:
        verbose_name = "State"
        verbose_name_plural = "States"
        permissions = (
            ('access_state', 'Can access States'),
        )

    COUNTRIES = (
        ('India', 'India'),
        ('USA', 'USA'),
        ('Thailand', 'Thailand'),
    )

    # Managers
    objects = StateManager()

    # Database fields
    name = models.CharField(
        'Name',
        max_length=100,
        unique=True,
        help_text='''
        100 chars max
        '''
    )
    code = models.CharField(
        'Code',
        max_length=10,
        unique=True,
        help_text='''
        10 chars max
        ''',
        null=True, blank=True
    )
    country = models.CharField(
        max_length=50,
        default="India",
        choices=COUNTRIES,
        blank=False,
        null=False
    )

    def __str__(self):
        return self.name

    def natural_key(self):
        return self.name

我的夹具文件如下

    [
    {
        "model": "parties.state",
        "fields": {
            "name": "Andaman and Nicobar",
            "code": "AN",
            "country": "India"
        }
    },
    {
        "model": "parties.state",
        "fields": {
            "name": "Andhra Pradesh",
            "code": "AP",
            "country": "India"
        }
    },
]

我之前已将数据转储到夹具文件中。但是当我现在尝试加载夹具时,出现以下错误...

Traceback (most recent call last):
.....
.....
  TypeError: get_by_natural_key() takes 2 positional arguments but 20 were given
.....
.....

  File "/home/parijath/Projects/virtualenv/django18/lib/python3.4/site-packages/django/core/serializers/base.py", line 195, in build_instance
    obj.pk = Model._default_manager.db_manager(db).get_by_natural_key(*natural_key).pk
django.core.serializers.base.DeserializationError: Problem installing fixture '/home/parijath/Projects/django_projects/webportal18_multipleapps/parties/fixtures/states.json': get_by_natural_key() takes 2 positional arguments but 20 were given

最佳答案

natural_key方法应该返回一个元组,而不是一个字符串。

def natural_key(self):
    return (self.name,)

如果 natural_key 是字符串 "Andaman and Nicobar" 而不是元组 ('Andaman and Nicobar',) 那么 *natural_key 将字符串中的 19 个字符中的每一个解压缩为单独的参数。与 self 一起,它为您提供了错误消息中的 20 个参数。

关于python - 从夹具加载数据时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34636107/

相关文章:

python - 具有多个连接的 Django ORM 查询

python - 使用区分大小写和不区分大小写的混合模式的正则表达式查找文本中使用的人称代词的数量

python - 在字典中查找 X 和 Y 的最大和最小坐标

python - 如何将 MYSQL Latin-1 GEOMETRY 字段转换为 UTF8 以使其与 Django 一起使用?

django - docker-compose - 数据库迁移和其他前/后脚本

python - 导入错误 : No module named books. 型号

Django 通过不同于 id 生成组

python - Python和OpenCV:Exe文件中的IP摄像机断言失败

python - 为什么当列表更新时,由列表元素组成的元组会发生变化

python - 如何在 django-registration 中设置注销 url?