VA splash
VA splash

Reputation: 573

Django : defining method inside the models

serialize() method included in the django Tools_booked class but while trying to access that method it shows error.

'QuerySet' object has no attribute 'serialize'

models.py

from django.core.serializers import serialize
class UpdateQuerySet(models.QuerySet):
    def serialize(self):
        print("*****Entered the serizlize inside the  UpdateQuerySet models **********")
        qs = self
        return serialize('json', qs, fields=('auto_increment_id','user','component','booked'))

class UpdateManager(models.Manager):
    def get_queryset(self):
        return UpdateQuerySet(self.model, using=self._db)

class Tools_booked(models.Model):
    auto_increment_id = models.AutoField(primary_key=True)
    user=models.ForeignKey(Profile, on_delete=models.CASCADE)
    component = models.CharField(max_length=30, blank=True)
    booked = models.DateTimeField(auto_now_add=True,blank=True)

    objects = UpdateManager()

    def __str__(self):
        return self.component

    def serialize(self):
        json_data = serialize("json", [self], fields=['auto_increment_id','user','component','booked'])
        stuct = json.loads(json_data)
        print(struct)
        data = json.dump(stuct[0]['fields'])
        return data

views.py

class SerializedDetialView(View):
     def get(self, request, *args, **kwargs):
        print("*****Entered the SerializedDetialView **********")
        obj_list= Tools_booked.objects.filter(auto_increment_id=1)
        json_data = obj_list.serialize()
        return HttpResponse(json_data, content_type='application/json')


class SerializedListView(View):
     def get(self, request, *args, **kwargs):
        json_data = Tools_booked.objects.all().serialize()
        return HttpResponse(json_data, content_type='application/json')

The error traceback

 json_data = Tools_booked.objects.all().serialize()
AttributeError: 'QuerySet' object has no attribute 'serialize'

But this works.

class SerializedDetialView(View):
     def get(self, request, *args, **kwargs):
        obj_list= Tools_booked.objects.filter(auto_increment_id=1)
        json_data = serializers.serialize("json", obj_list )
        return HttpResponse(json_data, content_type='application/json')


class SerializedListView(View):
     def get(self, request, *args, **kwargs):
        qs = Tools_booked.objects.all()
        json_data = serializers.serialize("json", qs )
        return HttpResponse(json_data, content_type='application/json')

How to use the serialize() method inside the models.py ,Tools_booked class.

Upvotes: 1

Views: 992

Answers (3)

gtrax147
gtrax147

Reputation: 1

In your models

class UpdateManager(models.Manager):
    def get_queryset(self):
        return UpdateQuerySet(self.model, self._db)

    # Here for you to call to your views
    def serialize(self):
        return self.get_queryset().serialize()

In your views

json_data = Tools_booked.objects.all().serialize()

Django has changed a little bit. Here is this document for Django update version.

Upvotes: 0

Wariored
Wariored

Reputation: 1343

Here is what's working for me:

from django.core.serializers import serialize
from django.db import models


class UpdateQuerySet(models.QuerySet):
    def serialize(self):
        print("*****Entered the serizlize inside the  UpdateQuerySet models **********")
        return serialize('json', self, fields=('component','booked'))

class UpdateManager(models.Manager):
      # define here methods only needed inside this manager
       pass 

class Tools_booked(models.Model):
    component = models.CharField(max_length=30, blank=True)
    booked = models.DateTimeField(auto_now_add=True,blank=True)
    objects = models.Manager()
    serializer = UpdateManager.from_queryset(UpdateQuerySet)()

Now you can do in your views:

json_data = Tools_booked.serializer.serialize()

I guess you have an error because your serialize method is not defined inside the manager

Upvotes: 0

Muhammad Hassan
Muhammad Hassan

Reputation: 14391

You should either use Django-rest frameworks serializers with many=True or use values() function of Django queryset. There is no need to write a function in models. It will work like this

class YourSerializer(serializers.ModelSerializer):
     class Meta:
        model = "You Model Here"
        fields = "write list of your model fields here or user __all__ for all fields"

you can serialize your query like this

queryset = Your_Model.objects.all()
serialized = YourSerializer(queryset, many=True).data

Other way to do so is like this

serialized = Your_Model.objects.all().values()

This method look simple but if you are writing rest apis, you should use serializers. You can look into details of serializer here.

Upvotes: 1

Related Questions