Cannot serialize list of objects as JSON in Django - python

I'm trying to pass some data about a user as JSON, and because the User object has many-to-many relationships, serializing a user as JSON seems to only include the primary key of the m-n object.
(e.g. each user has hobbies, but in the JSON it will only have the PK of the hobbies)
Anyway, I tried constructing a schema to solve this as such:
[[{user}, [hobbies]], [{user}, [hobbies]],...]
But whenever I try to serialize this (in Python it's basically an array with an object and another array in it), I get the error:
'list' object has no attribute '_meta'
Why is this happening and how can I fix it?
EDIT:
Here's the code for it:
for u in allUsers:
if searchedHobby in u.hobbies.all():
user = [u]
userHobbies = []
for hobby in u.hobbies.all():
userHobbies.append(hobby.name)
user.append(userHobbies)
response.append(user)
data = serializers.serialize('json', response)

As seen in the django github repository the serialize method expects a queryset.
What you could do is to do a json.dumps(response) and return that in the HttpResponse.

Related

Django Json Field - Find objects hat do not have key

I have a Model with a JSON Field.
data = JSONField(default=dict)
Is there an efficient way - or queryset filter - to find all instances of this Model that do not have a speicfic key in the json field.
Django documentation includes has_key function for JSON field.
Essentially i'm looking for a way to do not_has_key
My current method:
queryset = MyObj.objects.all()
for obj in queryset:
if 'my_key' not in obj.data:
do_work()
else:
pass
#key_already_exists
Many thanks

Convert Django queryset to dictionnary in a JSON serialization purpose

I'm creating an API and I need to return data in a dictionnary format sothat it can be serialized (by the API mechanism).
The code that currently works is something as simple as:
def mymethod(self):
queryset1 = MyClass.objects.get(...) # Ccontains 1 object, easy to deal with
queryset2 = OtherClass.objects.filter(...) # Contains N objects, hard to deal with !
return {
'qs1_result': queryset1.some_attribute # This works well
}
Returning data from queryset1 is easy because there is 1 object. I just pick the attribute I need and it works. Now let's say that in addition, I want to return data from queryset2, where there are many objects, and that I don't need every attributes of the object.
How would you do that?
I repeat that I do NOT need to make the serialization myself. I just need to return structured data sothat the serialization can be made.
Thanks a lot.
From the Django docs: https://docs.djangoproject.com/en/dev/topics/serialization/#subset-of-fields
Subset of fields
If you only want a subset of fields to be serialized, you can specify a fields argument to the serializer:
from django.core import serializers
data = serializers.serialize('json', SomeModel.objects.all(), fields=('name','size'))
In this example, only the name and size attributes of each model will be serialized.

How to get dictionary object in Mongoengine Python?

On querying pymongo i get a dictionary object that can be sent directly as a response to the api request. Where as mongoengine returns a Document object on querying database. So I have to parse every object before it can be sent as the response in the api.
this is how I have to query in mongoengine.
users = User.objects(location = 'US')
This will return me a BaseQueryList object which contains User model type object. Instead I need that it should return me a list of dictionary type objects of Users.
In BaseQueryList there is one method called as_pymongo, we can use this to get rows as list of dict like where we get pymongo. The following is an example
users = User.objects(location = 'US').as_pymongo()
OR
In BaseQueryList there are in list of User class objects.
In User class object there is one method called _data, this will returns data as dict
So you can try like following
users = [user._data for user in users._iter_results()]
It could be help you.
Mongoengine has to_mongo() method that gives you Python dict.
users = User.objects(location = 'US')
users.to_mongo()

Django: how to retrieve an object selected by the ``object_detail`` generic view?

Hi (sorry for my ugly english)
I wonder if this is possible to retrieve an object which was selected with the object_detail generic view. For example :
from django.views.generic.list_detail import object_detail
def my_view(request, slug)
response = object_detail(request, MyModel.objects.all(),
slug=slug,
slug_field='slug',
template_object_name='object')
# Here I need my object in ``response`` to do something after.
I don't know where is the object
You can't get the object this way, since object_detail simply returns a rendered response. If you need it, you'll just have to get it manually:
object = MyModel.objects.get(slug=slug)

Django serializer gives 'str' object has no attribute '_meta' error

I am trying to make Django view that will give JSON responce with earliest and latest objects. But unfotunately it fails to work with this error.
'str' object has no attribute '_meta'
I have other serialization and it works.
Here is the code.
def get_calendar_limits(request):
result = serializers.serialize("json", Session.objects.aggregate(Max('date'), Min('date')), ensure_ascii=False)
return HttpResponse(result, mimetype="application/javascript")
Thanks a lot beforehand.
I get the same error when trying to serialize an object that is not derived from Django's Model
Python has "json" module. It can 'dumps' and 'loads' function. They can serialize and deserialize accordingly.
Take a look at the following:
objects= Session.objects.aggregate(Max('date'), Min('date'))
print [ type[o] for o in objects ]
result = serializers.serialize("json", objects, ensure_ascii=False)
You might want to just run the above in interactive Python as an experiment.
What type are your objects? Is that type serializable?

Categories