I have these models:
class Projects(models.Model):
projectName =models.CharField(max_length = 100,unique=True,db_index=True)
projectManager = EmbeddedModelField('Users')
class Users(models.Model):
name = models.CharField(max_length = 100,unique=True)
designation = models.CharField(max_length =100 )
I need to return JSON from my view for all Projects objects,I tried json.dumps(Projects.objects.all()) but it did not worked,how do i accomplished it??
EDIT:
I used json.dumps(Projects.objects.all().values()) and got this:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "D:\Python27\lib\json\__init__.py", line 238, in dumps
**kw).encode(obj)
File "D:\Python27\lib\json\encoder.py", line 203, in encode
chunks = list(chunks)
File "D:\Python27\lib\json\encoder.py", line 436, in _iterencode
o = _default(o)
File "D:\Python27\lib\json\encoder.py", line 178, in default
raise TypeError(repr(o) + " is not JSON serializable")
TypeError: [{'projectName': u'HELLO', 'projectManager': {u'id': u'4eb3b792b990a24e49f6bb26', u'name': u'anshul', u'designation': u'programmer', u'teams': []}, '
id': u'4eb3b7d0e814520db4000000'}] is not JSON serializable
Now i am getting the result what i want but why is this giving me error as well.
Try Jason.dumps-ing the result of Queryset.values().
Querysets are not serializable. You could try to use list(self.objects) instead self.objects to force the queryset to be processed as a list. In your case try something like this
json.dumps(list(Projects.objects.all().values()))
Related
I'm using sessions in a current django project and recently got a 'Object of type 'date' is not JSON serializable' error - due to the move_in_date field below.
When saving a modelform of the below model to the session via:
if form.is_valid():
request.session.update(form.cleaned_data)
my model:
class Address(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
house_name_number = models.CharField(max_length=255, verbose_name="house name or number")
street_name = models.CharField(max_length=255)
town_city = models.CharField(max_length=255)
county = models.CharField(max_length=255)
postcode = models.CharField(max_length=8)
same_address = models.BooleanField()
move_in_date = models.DateField(null=True, blank=True)
I've tried to solve the issue by using DjangoJSONEncoder as suggested by the docs, which can handle datetimes via the settings with SESSION_SERIALIZER=DjangoJSONEncoder (should this be a serializer rather than an encoder?), but trying that or SESSION_SERIALIZER=PickleSerializer both give an Attribute error - ... has no attribute 'rsplit'
Additionally I was using django wizard before which stores intermediate data (such as the field causing the date issue above) in the session. I've now switched that part of the app to use seperate views for flexibility (as signup wasn't just a linear path), django wizard doesn't have this issue, how does it get round this?
Updated with stacktrace
Traceback (most recent call last):
File "/Users/Barclay/.virtualenvs/switcher5/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner
response = get_response(request)
File "/Users/Barclay/.virtualenvs/switcher5/lib/python3.6/site-packages/django/utils/deprecation.py", line 142, in __call__
response = self.process_response(request, response)
File "/Users/Barclay/.virtualenvs/switcher5/lib/python3.6/site-packages/django/contrib/sessions/middleware.py", line 58, in process_response
request.session.save()
File "/Users/Barclay/.virtualenvs/switcher5/lib/python3.6/site-packages/django/contrib/sessions/backends/db.py", line 83, in save
obj = self.create_model_instance(data)
File "/Users/Barclay/.virtualenvs/switcher5/lib/python3.6/site-packages/django/contrib/sessions/backends/db.py", line 69, in create_model_instance
session_data=self.encode(data),
File "/Users/Barclay/.virtualenvs/switcher5/lib/python3.6/site-packages/django/contrib/sessions/backends/base.py", line 98, in encode
serialized = self.serializer().dumps(session_dict)
File "/Users/Barclay/.virtualenvs/switcher5/lib/python3.6/site-packages/django/core/signing.py", line 93, in dumps
return json.dumps(obj, separators=(',', ':')).encode('latin-1')
File "/usr/local/Cellar/python3/3.6.0/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/__init__.py", line 238, in dumps
**kw).encode(obj)
File "/usr/local/Cellar/python3/3.6.0/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/usr/local/Cellar/python3/3.6.0/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "/usr/local/Cellar/python3/3.6.0/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/encoder.py", line 180, in default
o.__class__.__name__)
TypeError: Object of type 'date' is not JSON serializable
Stack trace for trying DjangoJSONEncoder:
Traceback (most recent call last):
File "/Users/Barclay/.virtualenvs/switcher5/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner
response = get_response(request)
File "/Users/Barclay/.virtualenvs/switcher5/lib/python3.6/site-packages/django/utils/deprecation.py", line 138, in __call__
response = self.process_request(request)
File "/Users/Barclay/.virtualenvs/switcher5/lib/python3.6/site-packages/django/contrib/sessions/middleware.py", line 20, in process_request
request.session = self.SessionStore(session_key)
File "/Users/Barclay/.virtualenvs/switcher5/lib/python3.6/site-packages/django/contrib/sessions/backends/db.py", line 18, in __init__
super(SessionStore, self).__init__(session_key)
File "/Users/Barclay/.virtualenvs/switcher5/lib/python3.6/site-packages/django/contrib/sessions/backends/base.py", line 51, in __init__
self.serializer = import_string(settings.SESSION_SERIALIZER)
File "/Users/Barclay/.virtualenvs/switcher5/lib/python3.6/site-packages/django/utils/module_loading.py", line 15, in import_string
module_path, class_name = dotted_path.rsplit('.', 1)
AttributeError: type object 'DjangoJSONEncoder' has no attribute 'rsplit'
A few things of confusion are hitting you:
When setting the serializer, do not provide a class reference, but a dotted part. This is seen in the error:
module_path, class_name = dotted_path.rsplit('.', 1)
DjangoJSONEncoder isn't the right fix for a serializer. It is referenced in the documentation as a way to serialize models before putting them into the session.
If you want to make a smart serializer then you still need to create a Serializer, which should support a dumps and loads interface, that leverage a JsonEncoder and JsonDecoder respectively.
The Pickle serializer will work just fine, but as said you need to provide the dotted path.
If you want to use JSON as serializer, then this might be a good start:
from django.core.serializers.json import DjangoJSONEncoder
from django.core.signing import JSONSerializer as BaseJSONSerializer
class SmartJSONSerializer(BaseJSONSerializer):
def dumps(self, obj):
return json.dumps(obj, separators=(',', ':'), cls=DjangoJSONEncoder).encode('latin-1')
I have below model and I want to perform below query:
Post.objects.select_related(
'previous_post', 'next_post'
).get(id=some_id)
# models.py
class Post(models.Model):
title = models.CharField(max_length=60, unique=True)
description = models.TextField()
content = models.TextField()
previous_post = models.OneToOneField('self', null=True, blank=True,
related_name='next_post',
on_delete=models.PROTECT)
For some reason it does not work with next_post parameter, as I get following error:
raise IndexError("Number of args exceeds number of fields")
IndexError: Number of args exceeds number of fields
Theoretically I can live without select_related, but I would prefer not to give up it in this case and I am really curious whether I am doing something wrong or this is just a Django bug.
Full traceback:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/home/konrad/PycharmProjects/jdg/env/lib/python3.4/site-packages/django/db/models/query.py", line 381, in get
num = len(clone)
File "/home/konrad/PycharmProjects/jdg/env/lib/python3.4/site-packages/django/db/models/query.py", line 240, in __len__
self._fetch_all()
File "/home/konrad/PycharmProjects/jdg/env/lib/python3.4/site-packages/django/db/models/query.py", line 1074, in _fetch_all
self._result_cache = list(self.iterator())
File "/home/konrad/PycharmProjects/jdg/env/lib/python3.4/site-packages/django/db/models/query.py", line 72, in __iter__
rel_populator.populate(row, obj)
File "/home/konrad/PycharmProjects/jdg/env/lib/python3.4/site-packages/django/db/models/query.py", line 1715, in populate
obj = self.model_cls.from_db(self.db, self.init_list, obj_data)
File "/home/konrad/PycharmProjects/jdg/env/lib/python3.4/site-packages/django/db/models/base.py", line 460, in from_db
new = cls(*values)
File "/home/konrad/PycharmProjects/jdg/env/lib/python3.4/site-packages/django/db/models/base.py", line 372, in __init__
raise IndexError("Number of args exceeds number of fields")
IndexError: Number of args exceeds number of fields
It looks like a bug in Django. I can reproduce in 1.8 and 1.9, but not in the master branch.
Doing a git bisect, tt appears to have been fixed by ticket 26207, so it should be fixed in Django 1.10.
I am using Django (master branch) and Haystack (master branch) connected to an Elasticsearch server. The Python version is 3.4.
The search index class looks like this:
class PageIndex(indexes.SearchIndex, indexes.Indexable):
text = fields.EdgeNgramField(document=True)
name = fields.EdgeNgramField(model_attr='name', boost=2)
tags = fields.EdgeNgramField(model_attr='tags', boost=1.5)
description = fields.EdgeNgramField(model_attr='description_summary', boost=0.9)
def get_model(self):
return Page
def index_queryset(self, using=None):
return self.get_model().objects.filter(created__lte=datetime.datetime.now())
When I try to create the index, I get the following error:
> python manage.py update_index Indexing 7 communities
PUT /haystack [status:400 request:0.013s]
ERROR:root:Error updating page using default
Traceback (most recent call last):
File "/env/lib/python3.4/site-packages/haystack/management/commands/update_index.py", line 221, in handle_label
self.update_backend(label, using)
File "/env/lib/python3.4/site-packages/haystack/management/commands/update_index.py", line 266, in update_backend
do_update(backend, index, qs, start, end, total, self.verbosity)
File "/env/lib/python3.4/site-packages/haystack/management/commands/update_index.py", line 89, in do_update
backend.update(index, current_qs)
File "/env/lib/python3.4/site-packages/haystack/backends/elasticsearch_backend.py", line 158, in update
prepped_data = index.full_prepare(obj)
File "/env/lib/python3.4/site-packages/haystack/indexes.py", line 204, in full_prepare
self.prepared_data = self.prepare(obj)
File "/env/lib/python3.4/site-packages/haystack/indexes.py", line 187, in prepare
ID: get_identifier(obj),
File "/env/lib/python3.4/site-packages/haystack/utils/__init__.py", line 33, in default_get_identifier
obj_or_string._meta.module_name,
AttributeError: 'Options' object has no attribute 'module_name'
You receiving this error message because in Django >= 1.6 Options.module_name changed to .model_name (this is widley abused non-public API) so you just need change in haystack code module_name
You have to check that you have an attribute named "name" in your models.
models.py
class Page(models.Model):
name = models.CharField(max_length=20)
search_index.py
class PageIndex(indexes.SearchIndex, indexes.Indexable):
name = fields.EdgeNgramField(model_attr='name', boost=2)
I am always getting this error TypeError: not all arguments converted during string formatting
Here is my query
State.objects.raw('...review_create_date between %s and %s group by error_type',[fromdate,todate])
Here fromdate=2011-05-21 and todate='2011-05-27'
The above query executes in mysql prompt but could not able to run in python shell
Please some one help me
Here is the traceback
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/usr/local/lib/python2.6/dist-packages/django/db/models/query.py", line 1412, in __iter__
query = iter(self.query)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/query.py", line 73, in __iter__
self._execute_query()
File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/query.py", line 87, in _execute_query
self.cursor.execute(self.sql, self.params)
File "/usr/local/lib/python2.6/dist-packages/django/db/backends/util.py", line 18, in execute
sql = self.db.ops.last_executed_query(self.cursor, sql, params)
File "/usr/local/lib/python2.6/dist-packages/django/db/backends/__init__.py", line 216, in last_executed_query
return smart_unicode(sql) % u_params
TypeError: not all arguments converted during string formatting
django raw sql query in view
I also faced this issue, so I changes the old formatting to new using
format. I it works for me.
models.py
class VehicleDamage(models.Model):
requestdate = models.DateTimeField("requestdate")
vendor_name = models.CharField("vendor_name", max_length=50)
class Meta:
managed=False
views.py
def location_damageReports(request):
#static date for testing
date_from = '2019-11-01'
date_to = '2019-21-01'
vehicle_damage_reports = VehicleDamage.objects.raw("SELECT * FROM VendorReport_vehicledamage WHERE requestdate BETWEEN '{0}' AND '{1}'".format(date_from, date_to))
damage_report = DashboardDamageReportSerializer(vehicle_damage_reports, many=True)
data={"data": damage_report.data}
return HttpResponse(json.dumps(data), content_type="application/json")
Try using ? instead of %s.
I have a model which can be attached to to other models.
class Attachable(models.Model):
content_type = models.ForeignKey(ContentType)
object_pk = models.TextField()
content_object = generic.GenericForeignKey(ct_field="content_type", fk_field="object_pk")
class Meta:
abstract = True
class Flag(Attachable):
user = models.ForeignKey(User)
flag = models.SlugField()
timestamp = models.DateTimeField()
I'm creating a generic relationship to this model in another model.
flags = generic.GenericRelation(Flag)
I try to get objects from this generic relation like so:
self.flags.all()
This results in the following exception:
>>> obj.flags.all()
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/usr/local/lib/python2.6/dist-packages/django/db/models/manager.py", line 105, in all
return self.get_query_set()
File "/usr/local/lib/python2.6/dist-packages/django/contrib/contenttypes/generic.py", line 252, in get_query_set
return superclass.get_query_set(self).filter(**query)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/query.py", line 498, in filter
return self._filter_or_exclude(False, *args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/query.py", line 516, in _filter_or_exclude
clone.query.add_q(Q(*args, **kwargs))
File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/query.py", line 1675, in add_q
can_reuse=used_aliases)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/query.py", line 1569, in add_filter
negate=negate, process_extras=process_extras)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/query.py", line 1737, in setup_joins
"Choices are: %s" % (name, ", ".join(names)))
FieldError: Cannot resolve keyword 'object_id' into field. Choices are: content_type, flag, id, nestablecomment, object_pk, timestamp, user
>>> obj.flags.all(object_pk=obj.pk)
Traceback (most recent call last):
File "<console>", line 1, in <module>
TypeError: all() got an unexpected keyword argument 'object_pk'
What have I done wrong?
You need to define object_id_field and content_type_field when creating GenericRelation:
flags = generic.GenericRelation(Flag, object_id_field="object_pk", content_type_field="content_type")