Hi there i am new ot django and django rest framework and i am having torouble when using serializers with PrimarayKeyTelatedFields() the code below is my code for my models.py
from django.db import models
class Author(models.Model):
name = models.CharField(max_length=50)
age = models.IntegerField(default=0)
class Book(models.Model):
name = models.CharField(max_length=40)
author = models.ForeignKey(to=Author, on_delete=models.CASCADE)
below is my serializer code
from rest_framework import serializers
from books.models import Book, Author
class BookSerializer(serializers.ModelSerializer):
author_id = serializers.PrimaryKeyRelatedField(many=False,
queryset=Author.objects.all())
class Meta:
model = Book
fields = ['id', 'name', 'author_id']
class AuthorSerializer(serializers.ModelSerializer):
class Meta:
model = Author
fields = ['id', 'name', 'age']
and when i try to execute following commands in shell
>>from books.api.serializers import BookSerializer, AuthorSerializer
>> play1 = BookSerializer(data = { 'author_id':1 ,'name':'book1' })
>>play1.is_valid()
True
>>play1.save()
After executing above i got the huge error as i pasted below
Traceback (most recent call last):
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\fields\__init__.py", line 1988, in get_prep_value
return int(value)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'Author'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\rest_framework\serializers.py", line 962, in create
instance = ModelClass._default_manager.create(**validated_data)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\query.py", line 514, in create
obj.save(force_insert=True, using=self.db)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\base.py", line 806, in save
self.save_base(
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\base.py", line 857, in save_base
updated = self._save_table(
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\base.py", line 1000, in _save_table
results = self._do_insert(
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\base.py", line 1041, in _do_insert
return manager._insert(
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\query.py", line 1434, in _insert
return query.get_compiler(using=using).execute_sql(returning_fields)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\sql\compiler.py", line 1620, in execute_sql
for sql, params in self.as_sql():
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\sql\compiler.py", line 1547, in as_sql
value_rows = [
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\sql\compiler.py", line 1548, in <listcomp>
[
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\sql\compiler.py", line 1549, in <listcomp>
self.prepare_value(field, self.pre_save_val(field, obj))
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\sql\compiler.py", line 1487, in prepare_value
value = field.get_db_prep_save(value, connection=self.connection)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\fields\related.py", line 1126, in get_db_prep_save
return self.target_field.get_db_prep_save(value, connection=connection)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\fields\__init__.py", line 910, in get_db_prep_save
return self.get_db_prep_value(value, connection=connection, prepared=False)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\fields\__init__.py", line 2668, in get_db_prep_value
value = self.get_prep_value(value)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\fields\__init__.py", line 1990, in get_prep_value
raise e.__class__(
TypeError: Field 'id' expected a number but got <Author: Author object (1)>.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\rest_framework\serializers.py", line 212, in save
self.instance = self.create(validated_data)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\rest_framework\serializers.py", line 981, in create
raise TypeError(msg)
TypeError: Got a `TypeError` when calling `Book.objects.create()`. This may be because you have a writable field on the serializer class that is not a valid argument to `Book.objects.create()`. You may need to make the field read-only, or override the BookSerializer.create() method to handle this correctly.
Original exception was:
Traceback (most recent call last):
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\fields\__init__.py", line 1988, in get_prep_value
return int(value)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'Author'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\rest_framework\serializers.py", line 962, in create
instance = ModelClass._default_manager.create(**validated_data)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\query.py", line 514, in create
obj.save(force_insert=True, using=self.db)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\base.py", line 806, in save
self.save_base(
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\base.py", line 857, in save_base
updated = self._save_table(
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\base.py", line 1000, in _save_table
results = self._do_insert(
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\base.py", line 1041, in _do_insert
return manager._insert(
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\query.py", line 1434, in _insert
return query.get_compiler(using=using).execute_sql(returning_fields)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\sql\compiler.py", line 1620, in execute_sql
for sql, params in self.as_sql():
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\sql\compiler.py", line 1547, in as_sql
value_rows = [
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\sql\compiler.py", line 1548, in <listcomp>
[
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\sql\compiler.py", line 1549, in <listcomp>
self.prepare_value(field, self.pre_save_val(field, obj))
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\sql\compiler.py", line 1487, in prepare_value
value = field.get_db_prep_save(value, connection=self.connection)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\fields\related.py", line 1126, in get_db_prep_save
return self.target_field.get_db_prep_save(value, connection=connection)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\fields\__init__.py", line 910, in get_db_prep_save
return self.get_db_prep_value(value, connection=connection, prepared=False)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\fields\__init__.py", line 2668, in get_db_prep_value
value = self.get_prep_value(value)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\fields\__init__.py", line 1990, in get_prep_value
raise e.__class__(
TypeError: Field 'id' expected a number but got <Author: Author object (1)>.
you passed here an object instead of id..
author_id = serializers.PrimaryKeyRelatedField(many=False,
queryset=Author.objects.all())
you should pass an id like this
author_id = serializers.PrimaryKeyRelatedField(many=False,
queryset=Author.objects.get(id=request.user.id))
Remember whatever you queried it should be an int value not str or object
Cause
The problem is caused by setting author_id with serializer.PrimaryKeyRelatedField
Explanation
Django will internally auto-create an attribute for related fields (ForeignKey, OneToOneField, ...) with the suffix _id appending to the declared field name. The data type of this field is a number. In this case, the author field in Book will have an attribute called author_id. The problem comes from serializer.PrimaryKeyRelatedField returning a model instance in the serializer's validated data, causing field author_id to be set with Author instance. Resulting in an error.
Solution
Rename author_id attribute to author.
class BookSerializer(serializers.ModelSerializer):
author = serializers.PrimaryKeyRelatedField(queryset=Author.objects.all())
class Meta:
model = Book
fields = ['id', 'name', 'author']
Related
I have a model with a custom string for an id.
class BaseModel(Model):
id = CharField(
max_length=23,
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
default=generate,
editable=False,
)
When deleting, I am getting this error.
Internal Server Error: /admin/sampleapp/user/
Traceback (most recent call last):
File "path\to\sampleapp\venv\lib\site-packages\django\db\models\fields\__init__.py", line 1988, in get_prep_value
return int(value)
ValueError: invalid literal for int() with base 10: 'AC7EEKrEhYZ9p1r-Q'
The above exception was the direct cause of the following exception:
response = func(self, request, queryset)
File "path\to\sampleapp\venv\lib\site-packages\django\contrib\admin\actions.py", line 39, in delete_selected
) = modeladmin.get_deleted_objects(queryset, request)
File "path\to\sampleapp\venv\lib\site-packages\django\contrib\admin\options.py", line 2099, in get_deleted_objects
return get_deleted_objects(objs, request, self.admin_site)
File "path\to\sampleapp\venv\lib\site-packages\django\contrib\admin\utils.py", line 120, in get_deleted_objects
collector.collect(objs)
File "path\to\sampleapp\venv\lib\site-packages\django\contrib\admin\utils.py", line 186, in collect
return super().collect(objs, source_attr=source_attr, **kwargs)
File "path\to\sampleapp\venv\lib\site-packages\django\db\models\deletion.py", line 343, in collect
field.remote_field.on_delete(self, field, sub_objs, self.using)
File "path\to\sampleapp\venv\lib\site-packages\django\db\models\deletion.py", line 23, in CASCADE
collector.collect(
File "path\to\sampleapp\venv\lib\site-packages\django\contrib\admin\utils.py", line 186, in collect
return super().collect(objs, source_attr=source_attr, **kwargs)
File "path\to\sampleapp\venv\lib\site-packages\django\db\models\deletion.py", line 365, in collect
sub_objs = field.bulk_related_objects(new_objs, self.using)
File "path\to\sampleapp\venv\lib\site-packages\django\contrib\contenttypes\fields.py", line 524, in bulk_related_objects
return self.remote_field.model._base_manager.db_manager(using).filter(
File "path\to\sampleapp\venv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "path\to\sampleapp\venv\lib\site-packages\django\db\models\query.py", line 1071, in filter
return self._filter_or_exclude(False, args, kwargs)
File "path\to\sampleapp\venv\lib\site-packages\django\db\models\query.py", line 1089, in _filter_or_exclude
clone._filter_or_exclude_inplace(negate, args, kwargs)
File "path\to\sampleapp\venv\lib\site-packages\django\db\models\query.py", line 1096, in _filter_or_exclude_inplace
self._query.add_q(Q(*args, **kwargs))
File "path\to\sampleapp\venv\lib\site-packages\django\db\models\sql\query.py", line 1502, in add_q
clause, _ = self._add_q(q_object, self.used_aliases)
File "path\to\sampleapp\venv\lib\site-packages\django\db\models\sql\query.py", line 1532, in _add_q
child_clause, needed_inner = self.build_filter(
File "path\to\sampleapp\venv\lib\site-packages\django\db\models\sql\query.py", line 1448, in build_filter
condition = self.build_lookup(lookups, col, value)
File "path\to\sampleapp\venv\lib\site-packages\django\db\models\sql\query.py", line 1273, in build_lookup
lookup = lookup_class(lhs, rhs)
File "path\to\sampleapp\venv\lib\site-packages\django\db\models\lookups.py", line 27, in __init__
self.rhs = self.get_prep_lookup()
File "path\to\sampleapp\venv\lib\site-packages\django\db\models\lookups.py", line 276, in get_prep_lookup
rhs_value = self.lhs.output_field.get_prep_value(rhs_value)
File "path\to\sampleapp\venv\lib\site-packages\django\db\models\fields\__init__.py", line 1990, in get_prep_value
raise e.__class__(
ValueError: Field 'object_pk' expected a number but got 'AC7EEKrEhYZ9p1r-Q'.
"POST /admin/sampleapp/user/ HTTP/1.1" 500 213503
Kindly help in solving this issue.
I first noticed this issue when attempting to delete via admin but that didn't work. Upon inspection, I noticed the issue was that the model could not be deleted even via shell.
From your traceback:
ValueError: invalid literal for int() with base 10: 'AC7EEKrEhYZ9p1r-Q'
It's expecting an integer.
Is there a particular reason you want to replace the id field? You could always just create a separate field for your custom one and use that as the id elsewhere in your program
I am trying to implement bulk_create my inserting multiple objects in
a relation, not sure whether I am doing it right i have added trace back as well below is skill set model
class Skillset(models.Model):
skill_name = models.CharField(max_length=255)
def __str__(self):
return self.skill_name
my view
skill_name = request.POST.getlist('skill_name')
skill_level = request.POST.getlist('skill_level')
print(f'skill name-> {skill_name} skill level ->{skill_level}')
seeker_skll = []
# testing destructing
for skill_nme, skill_lvl in zip(skill_name, skill_level):
skill_set = Skillset.objects.get(skill_name=skill_nme)
seeker_skll.append(Seekerskillset(
skill_set=skill_set, skill_level=skill_lvl, seeker=user))
seeker_skll = Skillset.objects.bulk_create(seeker_skll)
print(seeker_skll)
return redirect('/users/dashboard')
Model
class Seekerskillset(models.Model):
skill_set = models.ForeignKey(Skillset, on_delete=models.CASCADE)
seeker = models.ForeignKey(SeekerProfile, on_delete=models.CASCADE)
skill_level = models.CharField(max_length=25)
class Meta:
verbose_name = 'Seeker skill set'
error i am getting
AttributeError: 'Seekerskillset' object has no attribute 'skill_name'
Traceback (most recent call last):
File "C:\Users\atif\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
response = get_response(request)
File "C:\Users\atif\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\atif\AppData\Local\Programs\Python\Python37\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "C:\Users\atif\PycharmProjects\my_proj\mysite_jobportal\seekerbuilder\views.py", line 43, in update_details
seeker_skll = Skillset.objects.bulk_create(seeker_skll)
File "C:\Users\atif\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\atif\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\query.py", line 515, in bulk_create
objs_without_pk, fields, batch_size, ignore_conflicts=ignore_conflicts,
File "C:\Users\atif\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\query.py", line 1293, in _batched_insert
self._insert(item, fields=fields, using=self.db, ignore_conflicts=ignore_conflicts)
File "C:\Users\atif\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\query.py", line 1270, in _insert
return query.get_compiler(using=using).execute_sql(returning_fields)
File "C:\Users\atif\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\sql\compiler.py", line 1415, in execute_sql
for sql, params in self.as_sql():
File "C:\Users\atif\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\sql\compiler.py", line 1360, in as_sql
for obj in self.query.objs
File "C:\Users\atif\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\sql\compiler.py", line 1360, in <listcomp>
for obj in self.query.objs
File "C:\Users\atif\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\sql\compiler.py", line 1359, in <listcomp>
[self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields]
File "C:\Users\atif\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\sql\compiler.py", line 1310, in pre_save_val
return field.pre_save(obj, add=True)
File "C:\Users\atif\AppData\Local\Programs\Python\Python37\lib\site-packages\django\db\models\fields\__init__.py", line 822, in pre_save
return getattr(model_instance, self.attname)
Exception Type: AttributeError at /users/app_det/
Exception Value: 'Seekerskillset' object has no attribute 'skill_name'
The problem is caused by using Skillset to bulk create Seekerskillset objects.
So change:
seeker_skll = Skillset.objects.bulk_create(seeker_skll)
to:
seeker_skll = Seekerskillset.objects.bulk_create(seeker_skll)
I have 2 models in my django project. DB is mongoDB and I use Djongo.
Here are the models:
class Item(models.Model):
item_id = models.IntegerField(primary_key=True)
item_name = models.CharField(max_length=30)
def __str__(self):
return f'<{self.item_name}>'
class Items(models.Model):
items_id = models.IntegerField(primary_key=True)
inventory = models.ArrayField(model_container=Item,)
neutral_item = models.EmbeddedField(model_container=Item,)
buffs = models.ArrayField(model_container=Item,)
def __str__(self):
return f'<{self.inventory}, {self.neutral_item}>'
When I do:
item = Item(item_name='Helmet')
items = Items(inventory=[item])
I am getting this TypeError:
'Item' object is not subscriptable
What is wrong?
Whole error message:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/Users/georgii/PycharmProjects/custom_hero_chaos/venv/lib/python3.8/site-packages/django/db/models/base.py", line 745, in save
self.save_base(using=using, force_insert=force_insert,
File "/Users/georgii/PycharmProjects/custom_hero_chaos/venv/lib/python3.8/site-packages/django/db/models/base.py", line 782, in save_base
updated = self._save_table(
File "/Users/georgii/PycharmProjects/custom_hero_chaos/venv/lib/python3.8/site-packages/django/db/models/base.py", line 887, in _save_table
results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw)
File "/Users/georgii/PycharmProjects/custom_hero_chaos/venv/lib/python3.8/site-packages/django/db/models/base.py", line 924, in _do_insert
return manager._insert(
File "/Users/georgii/PycharmProjects/custom_hero_chaos/venv/lib/python3.8/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/Users/georgii/PycharmProjects/custom_hero_chaos/venv/lib/python3.8/site-packages/django/db/models/query.py", line 1204, in _insert
return query.get_compiler(using=using).execute_sql(returning_fields)
File "/Users/georgii/PycharmProjects/custom_hero_chaos/venv/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1390, in execute_sql
for sql, params in self.as_sql():
File "/Users/georgii/PycharmProjects/custom_hero_chaos/venv/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1333, in as_sql
value_rows = [
File "/Users/georgii/PycharmProjects/custom_hero_chaos/venv/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1334, in <listcomp>
[self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields]
File "/Users/georgii/PycharmProjects/custom_hero_chaos/venv/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1334, in <listcomp>
[self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields]
File "/Users/georgii/PycharmProjects/custom_hero_chaos/venv/lib/python3.8/site-packages/django/db/models/sql/compiler.py", line 1275, in prepare_value
value = field.get_db_prep_save(value, connection=self.connection)
File "/Users/georgii/PycharmProjects/custom_hero_chaos/venv/lib/python3.8/site-packages/djongo/models/fields.py", line 215, in get_db_prep_save
return self.get_prep_value(value)
File "/Users/georgii/PycharmProjects/custom_hero_chaos/venv/lib/python3.8/site-packages/djongo/models/fields.py", line 222, in get_prep_value
processed_value = self._value_thru_fields('get_prep_value',
File "/Users/georgii/PycharmProjects/custom_hero_chaos/venv/lib/python3.8/site-packages/djongo/models/fields.py", line 315, in _value_thru_fields
post_dict = super()._value_thru_fields(func_name,
File "/Users/georgii/PycharmProjects/custom_hero_chaos/venv/lib/python3.8/site-packages/djongo/models/fields.py", line 145, in _value_thru_fields
field_value = value[field.attname]
TypeError: 'Item' object is not subscriptable
According to the Djongo docs for ArrayField you should instantiate like this:
entry = Entry()
entry.authors = [{'name': 'John', 'email': 'john#mail.com'},
{'name': 'Paul', 'email': 'paul#mail.com'}]
entry.save()
So in your case, you would do this.
items = Items()
items.inventory = [
{'item_name': 'Helmet'}
]
items.save()
I have a django model like this...
class ConversionResults(models.Model):
conversion_results_id = models.AutoField(primary_key=True)
conversion_rate_a = models.DecimalField(max_digits=4, decimal_places=2)
clicks_a = models.IntegerField()
conversion_rate_b = models.DecimalField(max_digits=4, decimal_places=2)
clicks_b = models.IntegerField()
week = models.IntegerField()
date = models.DateField()
time = models.TimeField()
objects = models.Manager()
class Meta:
db_table = 'conversion_results'
def __int__(self):
return self. conversion_results_id
When I try to add data to the model, like below
ConversionResults(
conversion_rate_a=conversion_rate_today_a,
conversion_rate_b=conversion_rate_today_b,
clicks_a=ctc_today_a,
clicks_b=ctc_today_b,
week=week,
date=today_date,
time=datetime.datetime.today().time() # the error is here
).save()
I am getting error with the time field as shown below
graphql.error.located_error.GraphQLLocatedError: [<class 'decimal.InvalidOperation'>]
I don't get how this is even related to decimal, the model contains a TimeField. Any help will be appreciated
Below is the full Traceback
Traceback (most recent call last):
File "/home/shashank/anaconda3/lib/python3.6/site-packages/promise/promise.py", line 487, in _resolve_from_executor
executor(resolve, reject)
File "/home/shashank/anaconda3/lib/python3.6/site-packages/promise/promise.py", line 754, in executor
return resolve(f(*args, **kwargs))
File "/home/shashank/anaconda3/lib/python3.6/site-packages/graphql/execution/middleware.py", line 75, in make_it_promise
return next(*args, **kwargs)
File "/home/shashank/project/server/data_distribution/query.py", line 416, in resolve_daily_updates
time=datetime.datetime.today().time() # the error is here
File "/home/shashank/anaconda3/lib/python3.6/site-packages/django/db/models/base.py", line 741, in save
force_update=force_update, update_fields=update_fields)
File "/home/shashank/anaconda3/lib/python3.6/site-packages/django/db/models/base.py", line 779, in save_base
force_update, using, update_fields,
File "/home/shashank/anaconda3/lib/python3.6/site-packages/django/db/models/base.py", line 870, in _save_table
result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "/home/shashank/anaconda3/lib/python3.6/site-packages/django/db/models/base.py", line 908, in _do_insert
using=using, raw=raw)
File "/home/shashank/anaconda3/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/shashank/anaconda3/lib/python3.6/site-packages/django/db/models/query.py", line 1186, in _insert
return query.get_compiler(using=using).execute_sql(return_id)
File "/home/shashank/anaconda3/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1331, in execute_sql
for sql, params in self.as_sql():
File "/home/shashank/anaconda3/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1275, in as_sql
for obj in self.query.objs
File "/home/shashank/anaconda3/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1275, in <listcomp>
for obj in self.query.objs
File "/home/shashank/anaconda3/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1274, in <listcomp>
[self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields]
File "/home/shashank/anaconda3/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1215, in prepare_value
value = field.get_db_prep_save(value, connection=self.connection)
File "/home/shashank/anaconda3/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 1563, in get_db_prep_save
return connection.ops.adapt_decimalfield_value(self.to_python(value), self.max_digits, self.decimal_places)
File "/home/shashank/anaconda3/lib/python3.6/site-packages/django/db/backends/base/operations.py", line 516, in adapt_decimalfield_value
return utils.format_number(value, max_digits, decimal_places)
File "/home/shashank/anaconda3/lib/python3.6/site-packages/django/db/backends/utils.py", line 238, in format_number
value = value.quantize(decimal.Decimal(1).scaleb(-decimal_places), context=context)
graphql.error.located_error.GraphQLLocatedError: [<class 'decimal.InvalidOperation'>]
I am using Django to perform a very simple function. The application will grow in size as time goes on, but for now, all I want to do is run through an html document of all my Facebook messages, and save a model for every user, and every message attached to that user. However when trying to create an instance of a model I created, FacebookUser, I get the error "NoneType" object is not callable. I read other SO articles, and browsed the internet for other issues, and found that the error usually stemmed from trying to do something with the class itself, and not an instantiation of the class. However I am creating an instance of this class, and still getting this error.
models.py
from django.db import models
class FacebookUser(models.Model):
full_name = models.CharField(max_length=255, null=True, blank=True)
def __str__(self):
return self.full_name
class Message(models.Model):
user = models.ForeignKey(FacebookUser)
content = models.TextField(max_length=10000, null=True, blank=True)
date_sent = models.DateTimeField(null=True, blank=True)
def __str__(self):
return '#{} {}'.format(self.id, self.user.full_name)
views.py
from django.http import HttpResponse
from facebook_user.models import FacebookUser, Message
from bs4 import BeautifulSoup
def crawl_messages(request):
data = open('messages.html', 'r').read()
soup = BeautifulSoup(data)
all_messages = soup.findAll("div", {"class": "message"})
msg_dictionaries = [{
'user': el.findAll('span')[0],
'time': el.findAll('span')[1],
'content': el.nextSibling.nextSibling
} for el in all_messages]
for msg in msg_dictionaries:
try:
fbuser = FacebookUser.objects.get(full_name=msg['user'])
print('Try One')
print(fbuser)
except FacebookUser.DoesNotExist:
fbuser = FacebookUser.objects.create(full_name=msg['user'])
print('Try Two')
print(fbuser)
except Exception as e:
print('Try Three')
print(e)
fbuser = None
if fbuser:
new_msg = Message()
new_msg.content = msg['content']
new_msg.user = fbuser
new_msg.save()
return HttpResponse('Worked ! Check the Admin')
Stack trace
Traceback (most recent call last):
File "/Users/timothybaney/Library/Python/3.5/lib/python/site-packages/django/core/handlers/base.py", line 149, in get_response
response = self.process_exception_by_middleware(e, request)
File "/Users/timothybaney/Library/Python/3.5/lib/python/site-packages/django/core/handlers/base.py", line 147, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/timothybaney/Data Science/facebook_sentiment_analysis/facebook_user/views.py", line 19, in crawl_messages
fbuser = FacebookUser.objects.create(full_name=msg['user'])
File "/Users/timothybaney/Library/Python/3.5/lib/python/site-packages/django/db/models/manager.py", line 122, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/Users/timothybaney/Library/Python/3.5/lib/python/site-packages/django/db/models/query.py", line 401, in create
obj.save(force_insert=True, using=self.db)
File "/Users/timothybaney/Library/Python/3.5/lib/python/site-packages/django/db/models/base.py", line 708, in save
force_update=force_update, update_fields=update_fields)
File "/Users/timothybaney/Library/Python/3.5/lib/python/site-packages/django/db/models/base.py", line 736, in save_base
updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "/Users/timothybaney/Library/Python/3.5/lib/python/site-packages/django/db/models/base.py", line 820, in _save_table
result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "/Users/timothybaney/Library/Python/3.5/lib/python/site-packages/django/db/models/base.py", line 859, in _do_insert
using=using, raw=raw)
File "/Users/timothybaney/Library/Python/3.5/lib/python/site-packages/django/db/models/manager.py", line 122, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/Users/timothybaney/Library/Python/3.5/lib/python/site-packages/django/db/models/query.py", line 1039, in _insert
return query.get_compiler(using=using).execute_sql(return_id)
File "/Users/timothybaney/Library/Python/3.5/lib/python/site-packages/django/db/models/sql/compiler.py", line 1059, in execute_sql
for sql, params in self.as_sql():
File "/Users/timothybaney/Library/Python/3.5/lib/python/site-packages/django/db/models/sql/compiler.py", line 1019, in as_sql
for obj in self.query.objs
File "/Users/timothybaney/Library/Python/3.5/lib/python/site-packages/django/db/models/sql/compiler.py", line 1019, in <listcomp>
for obj in self.query.objs
File "/Users/timothybaney/Library/Python/3.5/lib/python/site-packages/django/db/models/sql/compiler.py", line 1018, in <listcomp>
[self.prepare_value(field, self.pre_save_val(field, obj)) for field in fields]
File "/Users/timothybaney/Library/Python/3.5/lib/python/site-packages/django/db/models/sql/compiler.py", line 946, in prepare_value
value = value.resolve_expression(self.query, allow_joins=False, for_save=True)
TypeError: 'NoneType' object is not callable
This most likely means that msg['user'] is not a string, but an object that sets any attribute when that attribute is called. And thus it receives resolve_expression attribute that causes above error.
For a fix, try casting msg['user'] to a string in your create statement:
fbuser = FacebookUser.objects.create(str(msg['user'])
This is just a guess, without full source to run it there's no way to be certain.