Django - TypeError:int()参数必须是字符串或数字,而不是' dict'

时间:2016-12-23 07:50:15

标签: python django

我尝试保存多个Heat个实例并将其存储到列表heats,然后将列表用作bulk_create作为数据。

在我的models.py

class Animal(models.Model):

    farm = models.ForeignKey(Farm, related_name='farm_animals', on_delete=models.CASCADE)
    herd = models.ForeignKey(Herd, related_name='animals', on_delete=models.CASCADE)

    name = models.CharField(max_length=25)
    ....

class Heat(models.Model):

    # Relationship Fields
    animal = models.ForeignKey(Animal, related_name='heats', on_delete=models.CASCADE)

    # Fields
    ....

在我的views.py

@transaction.atomic
def create(self, request):
    heats = []
    for item in request.data:
        animal = Animal(item['animal'])
        heat = Heat(item['heat'])
        heat.animal = animal

        heats.append(heat)

    Heat.objects.bulk_create(heats)

request.data是json序列化的。这就是它的样子。

[
    {
        "animal" : {
            "id" : 1,
            ....
        },
        "heat" : {
            ....
        }
    },
    {
        "animal" : {
            "id" : 2,
            ....
        },
        "heat" : {
            ....
        }
    }, 
    {
        "animal" : {
            "id" : 3,
            ....
        },
        "heat" : {
            ....
        }
    }
]

但是我得到了错误:TypeError: int() argument must be a string or a number, not 'dict'

以下是完整的追溯:

Traceback (most recent call last):
  File "C:\Users\Web\Desktop\PyDev\Envs\djangular\lib\site-packages\django\core\handlers\exception.py", line 39, in inner
    response = get_response(request)
  File "C:\Users\Web\Desktop\PyDev\Envs\djangular\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\Web\Desktop\PyDev\Envs\djangular\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\Web\Desktop\PyDev\Envs\djangular\lib\site-packages\django\views\decorators\csrf.py", line 58, in wrapped_view
    return view_func(*args, **kwargs)
  File "C:\Users\Web\Desktop\PyDev\Envs\djangular\lib\site-packages\rest_framework\viewsets.py", line 83, in view
    return self.dispatch(request, *args, **kwargs)
  File "C:\Users\Web\Desktop\PyDev\Envs\djangular\lib\site-packages\rest_framework\views.py", line 477, in dispatch
    response = self.handle_exception(exc)
  File "C:\Users\Web\Desktop\PyDev\Envs\djangular\lib\site-packages\rest_framework\views.py", line 437, in handle_exception
    self.raise_uncaught_exception(exc)
  File "C:\Users\Web\Desktop\PyDev\Envs\djangular\lib\site-packages\rest_framework\views.py", line 474, in dispatch
    response = handler(request, *args, **kwargs)
  File "C:\Users\Web\Desktop\PyDev\Envs\djangular\lib\site-packages\django\utils\decorators.py", line 185, in inner
    return func(*args, **kwargs)
  File "C:\Users\Web\Desktop\PyDev\Envs\djangular\farm_management\heat\views.py", line 188, in create
    Heat.objects.bulk_create(heats)
  File "C:\Users\Web\Desktop\PyDev\Envs\djangular\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "C:\Users\Web\Desktop\PyDev\Envs\djangular\lib\site-packages\django\db\models\query.py", line 449, in bulk_create
    self._batched_insert(objs_with_pk, fields, batch_size)
  File "C:\Users\Web\Desktop\PyDev\Envs\djangular\lib\site-packages\django\db\models\query.py", line 1068, in _batched_insert
    self._insert(item, fields=fields, using=self.db)
  File "C:\Users\Web\Desktop\PyDev\Envs\djangular\lib\site-packages\django\db\models\query.py", line 1045, in _insert
    return query.get_compiler(using=using).execute_sql(return_id)
  File "C:\Users\Web\Desktop\PyDev\Envs\djangular\lib\site-packages\django\db\models\sql\compiler.py", line 1053, in execute_sql
    for sql, params in self.as_sql():
  File "C:\Users\Web\Desktop\PyDev\Envs\djangular\lib\site-packages\django\db\models\sql\compiler.py", line 1006, in as_sql
    for obj in self.query.objs
  File "C:\Users\Web\Desktop\PyDev\Envs\djangular\lib\site-packages\django\db\models\sql\compiler.py", line 945, in prepare_value
    value = field.get_db_prep_save(value, connection=self.connection)
  File "C:\Users\Web\Desktop\PyDev\Envs\djangular\lib\site-packages\django\db\models\fields\__init__.py", line 755, in get_db_prep_save
    prepared=False)
  File "C:\Users\Web\Desktop\PyDev\Envs\djangular\lib\site-packages\django\db\models\fields\__init__.py", line 938, in get_db_prep_value
    value = self.get_prep_value(value)
  File "C:\Users\Web\Desktop\PyDev\Envs\djangular\lib\site-packages\django\db\models\fields\__init__.py", line 946, in get_prep_value
    return int(value)
TypeError: int() argument must be a string or a number, not 'dict'

因为我是django开发的新手,所以我无法完全理解这种情况。请帮忙。

3 个答案:

答案 0 :(得分:1)

您应该从数据库中提取已存在的动物,而不是创建新的动物。为了提高性能,“散装”动物也是一个好主意。

代码:

iOS

答案 1 :(得分:0)

这是因为模型之间的外键关系。 如果您的模型有一个名为animal的ForeignKey,那么您的data_dict应该有一个animal_id字段。但是django.forms.model_to_dict()会返回带有动物场的字典 因此,您无法将动物字段重命名为MyModel(**model_to_dict(my_instance));

这样的事情应该有效:
animal_id

答案 2 :(得分:0)

create方法中,您应该将item['heat']作为kwargs传递并保存动物,然后再加热使用。 E.g。

@transaction.atomic
def create(self, request):
    heats = []
    for item in request.data:
        animal = Animal.objects.get(id=item['animal']['id'])
        heat = Heat(animal=animal, **item['heat'])

        heats.append(heat)

    Heat.objects.bulk_create(heats)