Reputation: 9443
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.
In my 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
@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. 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'
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. Please help.
Upvotes: 0
Views: 3070
Reputation: 9745
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)
Upvotes: 1
Reputation: 3257
In your create
method, you should pass item['heat']
as kwargs
and save animal before using it in heat. 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)
Upvotes: 0
Reputation: 216
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. But django.forms.model_to_dict()
returns a dict with an animal field.
So you can't do MyModel(**model_to_dict(my_instance));
you have to rename the animal field to animal_id
Something like this should work:
heat.animal_id = animal.id
Upvotes: 0