[英]Django - TypeError: int() argument must be a string or a number, not 'dict'
I'm trying to save a multiple Heat
instances and store it to a list heats
then used the list to a bulk_create
as data. 我想保存多个
Heat
实例,并将其存储到一个列表中heats
,然后用列表到bulk_create
数据。
In my models.py 在我的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
....
In my views.py 在我的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)
The request.data is a json serialized. request.data是序列化的json。 Here what it looks like.
在这里看起来像什么。
[
{
"animal" : {
"id" : 1,
....
},
"heat" : {
....
}
},
{
"animal" : {
"id" : 2,
....
},
"heat" : {
....
}
},
{
"animal" : {
"id" : 3,
....
},
"heat" : {
....
}
}
]
But i got the error: TypeError: int() argument must be a string or a number, not 'dict'
但是我得到了错误:
TypeError: int() argument must be a string or a number, not 'dict'
Here is the full traceback: 这是完整的回溯:
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'
I can't fully understand the situation since i am new to django development. 由于我不熟悉Django开发,因此我无法完全了解情况。 Please help.
请帮忙。
You should extract already existing animals from the database instead of creating new ones. 您应该从数据库中提取已经存在的动物,而不是创建新的动物。 And it's a good idea to extract the animals "in bulk" too to increase performance.
最好“大量”提取动物以提高性能。
The code: 编码:
@transaction.atomic
def create(self, request):
# Extracting animals
animal_id_list = [item['animal']['id'] for item in request.data]
animals = Animal.objects.in_bulk(animal_id_list)
animals_dict = {animal.id: animal for animal in animals}
# Creating heats
heats = []
for item in request.data:
heat = Heat(**item['heat'])
heat.animal = animals_dict[item['animal']['id']]
heats.append(heat)
Heat.objects.bulk_create(heats)
This is because of the foreign key relationship between models. 这是因为模型之间存在外键关系。 If your model has a ForeignKey called animal, then your
data_dict
should have an animal_id
field. 如果您的模型有一个名为animal的ForeignKey,则您的
data_dict
应该有一个animal_id
字段。 But django.forms.model_to_dict()
returns a dict with an animal field. 但是
django.forms.model_to_dict()
返回带有动物字段的字典。
So you can't do MyModel(**model_to_dict(my_instance));
所以你不能做
MyModel(**model_to_dict(my_instance));
you have to rename the animal field to animal_id
您必须将动物字段重命名为
animal_id
Something like this should work: 这样的事情应该起作用:
heat.animal_id = animal.id
In your create
method, you should pass item['heat']
as kwargs
and save animal before using it in heat. 在您的
create
方法中,应将item['heat']
传递为kwargs
并保存动物,然后再将其用于加热。 Eg 例如
@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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.