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.

Asked by: Freddie930 | Posted: 06-12-2021

Answer 1

I get the same error when trying to serialize an object that is not derived from Django's Model

Answered by: Leonardo572 | Posted: 07-01-2022

Answer 2

Python has "json" module. It can 'dumps' and 'loads' function. They can serialize and deserialize accordingly.

Answered by: Catherine542 | Posted: 07-01-2022

Answer 3

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?

Answered by: Dominik983 | Posted: 07-01-2022

Similar questions

python - Changing name of json attribute in serializer

How can I change the name of a json field response given by the serializer from the Django Rest Framework? After following the documentation I tried this, however it didn't work. from api.models import Countries from rest_framework import serializers class CountrySerializer(serializers.Serializer): country...

python - django rest 3.1.1 - one to many serializer with "many" attribute

I want to create a simple serializer that everyone who want will be able to add a Question with multi Answers (how many that he want) one Question- multi Answers I want to be able to add with the build in html form and not to edit the json. my models: class Question(models.Model): question_text = models.CharField(max_length=30) class Answer(models.Model...

python - Getting attribute error when trying to access the nested serializer in Django Rest Framework

I am getting following error while using the PostSerializer: Got AttributeError when attempting to get a value for field full_name on serializer UserSerializer. The serializer field might be named incorrectly and not match any attribute or key on the long instance. Original exception text was: 'long' object has no attribute 'full_name'. ...

python - Serializer List of objects grouping them by foreign key attribute

Similar to the issue found here (and maybe here) I had the problem of having a model like so: class Item(models.Model): name = models.CharField(max_lengt...

python - Django - Add attribute to serializer and order list based on Foreign Key

what I'm trying to get a data based on foreign keys. Let's say I have these models: # class Player(models.Model): name = models.CharField(max_length = 64) class Game(models.Model): score = models.IntegerField() player = models.ForeignKey('Player', models.DO_NOTHING, related_name='player', blank=False, null=False) class InjuredPlayer(models.Model): player = models.ForeignKey('Play...

Python - Django - Pass serializer and attribute as argument

currently i am dealing with this snippet: def to_representation(self, instance): representation = super().to_representation(instance) representation['categories'] = CategorySerializer(instance.categories, many=True).data return representation Now i would like to make the snippet representation['categories'] = CategorySerializer(instance.categories, many=True)....

python - How to create a json attribute for a serializer method result

Here I have a serializer and in that serializer is a get_is_liked method. This method is going to return a boolean, wheter the post has liked by the current user or not. Now, I want to get the result of this method in the format of a json attribute like other fields. There's suppose to be a mobile application that sends request for the logged in user to show if the post has liked before or not.

python - access attribute via serializer django

I got following models: class OrderItem(models.Model): ordered_amount = models.IntegerField(validators=[MinValueValidator(0)]) amount = models.IntegerField(default=0) order = models.ForeignKey( Order, on_delete=models.CASCADE, related_name="order_items" ) class Order(models.Model): reference = models.CharField(max_length=50) purchase_order = models.CharField(max_length=15, ...

python - Add a new attribute in serializer but doesn't appear

I want to add a new attribute apartment_sold in the Transaction serializer, but I seem it doesn't work! class TransactionSerializer(serializers.HyperlinkedModelSerializer): buyer = serializers.ReadOnlyField(source='buyer.username') apartment_sold = serializers.HyperlinkedRelatedField(view_name='sold-detail', read_only=True) class Meta: ...

python - Django serializer for one object

I'm trying to figure out a way to serialize some Django model object to JSON format, something like: j = Job.objects.get(pk=1) ############################################## #a way to get the JSON for that j variable??? ############################################## I don't want: from django.core import serializers serializers.serialize('json', Job.objects.get(pk=1),ensure_...

python - Django Serializer returns JSON for parent class objects only and leave child objects as same?

I have these models: class Projects(models.Model): projectName =models.CharField(max_length = 100,unique=True,db_index=True) projectManager = EmbeddedModelField('Users') class Teams(models.Model): teamType = models.CharField(max_length =100) teamLeader = EmbeddedModelField('Users') teamProject = EmbeddedModelField('Projects') class Users(models.Model): name = models.CharField(max_l...

python - Adding field that isn't in model to serializer in Django REST framework

I have a model Comment that when created may or may not create a new user. For this reason, my API requires a password field when creating a new comment. Here is my Comment model: class Comment(models.Model): commenter = models.ManyToManyField(Commenter) email = models.EmailField(max_length=100) author = models.CharField(max_length=100) url = models.URLField(max_length=200) content = mod...

python - Modifying the output from a serializer in the Django Rest Framework

I am using the django rest framework to output the content of an article. It works splendid, except now I want to modify the behavior to not return the full "content", but rather a teaser (of say the first 200 characters of the content but ideally I would like to be able to add any logic, say the end of the first sentence after 200 characters): class ArticleSerializer(serializers.HyperlinkedModelSerializ...

python - Using the serpent serializer for safe object pickling

As I understand it, using serpent is safer than pickle for serializing objects. I use the following class: import serpent class Test: def save(self, fileName) : ser = serpent.dumps({"schema": self}, indent=True) open(fileName, "wb" ).write(ser) def load(self, fileName) : self = serpent.load(open(fileName, "rb"))["schema"] def someFunction(self) : ...

python - Add user specific fields to Django REST Framework serializer

I want to add a field to a serializer that contains information specific to the user making the current request (I don't want to create a separate endpoint for this). Here is the way I did it: The viewset: class ArticleViewSet(viewsets.ModelViewSet): queryset = Article.objects.all() serializer_class = ArticleSerializer filter_class = ArticleFilterSet def prefetch_li...

python - Django Rest Framework serializer losing data

In my unittests, and in reality, the ModelSerializer class I've created just seems to discard a whole trove of data it is provided with: class KeyboardSerializer(serializers.ModelSerializer): user = serializers.Field(source='user.username') mappings = KeyMapSerializer(many=True, source='*') class Meta: model = Keyboard fields = ('user', 'label', 'is_primary', 'created', 'last_mo...

python - Changing name of json attribute in serializer

How can I change the name of a json field response given by the serializer from the Django Rest Framework? After following the documentation I tried this, however it didn't work. from api.models import Countries from rest_framework import serializers class CountrySerializer(serializers.Serializer): country...

python - Create a nested serializer with Django Rest Framework, but without primary keys as identity

I have two models to expose via an API: every RegionValue has a ForeignKey to a MapAnswer. I wish to represent this in our API built using rest_framework by making the RegionValues a field inside the MapAnswer endpoint. My rest_framework serializers looks like this: class RegionValueSerializer(serializers.ModelSeriali...

python - Rest framework serializer always returns False for is_valid

My serializer, quite basic: class TestSerializer(serializers.Serializer): date_time = serializers.DateTimeField() wanted to try out from shell but I get False each time I try to check it for validation. > import datetime > s=TestSerializer({'date_time': datetime.datetime(year=2012,month=12,day=12)} > {'date_time': datetime.datetime(2012, 12,...

Still can't find your answer? Check out these communities...

PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python