Django: 'QuerySet' object has no attribute 'serialize' - django

models.py
class UpdateQuerySet(models.QuerySet):
def serialize(self):
qs = self
return serialize('json', qs, fields=('user', 'content', 'image'))
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):
return serialize("json", [self], fields=['auto_increment_id','user','component','booked'])
in views.py
from django.core.serializers import serialize
class SerializedDetialView(View):
def get(self, request, *args, **kwargs):
obj = Tools_booked.objects.get(auto_increment_id=1)
json_data = obj.serialize()
return HttpResponse(json_data, content_type='application/json')
class SerializedListView(View):
def get(self, request, *args, **kwargs):
qs = Tools_booked.objects.all()
json_data = qs.serialize()
return HttpResponse(json_data, content_type='application/json')
I have seen the similar question, it is solved with a new class view. But why this code is not working. The error it showing for SerializedListView and SerializedDetialView urls is
'QuerySet' object has no attribute 'serialize'
and
'Tools_booked' object has no attribute 'serialize'
Why this error exist and how can we solve this error without creating a new class.
edit
in views.py, line 84, in get
json_data = qs.serialize()
AttributeError: 'QuerySet' object has no attribute 'serialize'

https://docs.djangoproject.com/en/3.0/topics/serialization/#serializing-data
from django.core import serializers
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')

Related

i am using django version 3 and when i tried to work on model managers i got this error

i am using django version 3 and when i tried to work on model managers i got this error
ModelManager is giving error
models.py
class ProductManager(models.Manager):
def get_queryset(self):
return ProductQuerySet(self.model, using=self._db)
def features(self):
return self.get_queryset().featured()
def get_by_id(self, id):
qs = self.get_queryset().filter(id=id)
if qs.count() == 1:
return qs.first()
return None
views.py
class ProductDetailView(DetailView):
template_name = "Products/details.html"
def get_context_data(self, *args, **kwargs):
context = super(ProductDetailView, self).get_context_data(*args, **kwargs)
print(context)
return context
def get_object(self, *args, **kwargs):
request = self.request
pk = self.kwargs.get('pk')
instance = Product.objects.get_by_id
if instance is None:
raise Http404('Product does not exist')
return instance
error:
AttributeError: 'Manager' object has no attribute 'get_by_id'
Well, the problem is that Django model object querysets don't have a method named 'get_by_id'. You should just use what's provided with Django. This is likely to be what you want:
Product.objects.get(id=1)
Substitute 1 by the id that you want..

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.
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.
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
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.

how to get url parameter in modelform

I have one model name is cityform
i want to get url parmeter in this CityFrom hwo can i do this?
here is my url
path('state/city/<int:id>/', City.as_view(), name="city")
http://localhost:8000/country/state/city/3/
here is my form
class
CityFrom(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(CityFrom,self).__init__(*args, **kwargs)
print(args)
print(kwargs)
self.fields['state'] = forms.ModelChoiceField(
empty_label = 'Select',
queryset = State.objects.all()
)
class Meta:
model = City
fields = ('state', 'name')
in this form i want to access id = 3
here is my view
from django.views import View
class City(View):
def get(self, request, *args, **kwargs):
Forms = CityFrom()
return render(request, 'albums/add.html', {'Forms': Forms})
Pass url parameter as keyword argument from views.py as following.
form = CityFrom(id=kwargs.get("id"))
To get the id in your forms.py, use following code in your form's __init__ method.
self.id = kwargs.get('id')
Your form should look like this.
CityFrom(forms.ModelForm):
def __init__(self, *args, **kwargs):
self.id = kwargs.get('id')
super(CityFrom,self).__init__(*args, **kwargs)
self.fields['state'] = forms.ModelChoiceField(
empty_label = 'Select',
queryset = State.objects.all()
)
class Meta:
model = City
fields = ('state', 'name')
* Call super after getting the id in your form as above. Here order of calling super is important.
Try
CityFrom(forms.ModelForm):
def __init__(self, *args, **kwargs):
self.id = kwargs.pop('id')
super(CityFrom,self).__init__(*args, **kwargs)

AttributeError - object has no attribute 'create'

I'm trying to save a through model which has the following attributes via Django-rest-framework
when sending a POST (I'm trying to create a new instance), I get the following error:
AttributeError at /api/organisation/provider/
'EnabledExternalProvider' object has no attribute 'create'
any ideas as to what i'm doing incorrectly?
the through model in question is:
class EnabledExternalProvider(models.Model):
provider = models.ForeignKey(ExternalProvider, related_name='associatedProvider')
organisation = models.ForeignKey(Organisation, related_name='associatedOrg')
enabled = models.BooleanField(default=True)
tenantIdentifier = models.CharField('Tenant identifer for organisation', max_length = 128, null=True, blank=True)
def __str__(self):
return self.provider + '-' + self.organisation
my view is:
class EnabledExternalProvider(mixins.RetrieveModelMixin, mixins.UpdateModelMixin,generics.GenericAPIView):
serializer_class = ConnectedServiceSerializer
def get_queryset(self):
return EnabledExternalProvider.objects.filter(organisation=self.request.user.organisation_id)
def get_object(self):
queryset = self.filter_queryset(self.get_queryset())
# make sure to catch 404's below
obj = queryset.get(organisation=self.request.user.organisation_id)
self.check_object_permissions(self.request, obj)
return obj
def get(self, request, *args, **kwargs):
return self.retrieve(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
return self.create(request, *args, **kwargs)
and my serializer is:
class ConnectedServiceSerializer(serializers.ModelSerializer):
provider=ExternalProviderSerializer(read_only=True)
organisation=OrganisationDetailSerializer(read_only=True)
class Meta:
model = EnabledExternalProvider
fields = ( 'organisation', 'enabled', 'tenantIdentifier')
read_only_fields = ('organisation', 'provider')
I'm POSTing the following:
{"provider":"1","tenantIdentifier":"9f0e40fe-3d6d-4172-9015-4298684a9ad2","enabled":true}
Your view doesn't have that method because you haven't defined it, or inherited from a class that has it; your mixins provide retrieve and update, but not create.
You could add mixins.CreateModelMixin to the inheritance, but at this point you should really be using a ViewSet instead.

POST not working Django Rest Framework

I find message return in google, not find.
Whats my code not post values correct?
I need help for solution correct.
As use form based generic views?
Im desenv an restAPI, i not understanding problem in my code, i running and return:
I retrieve message, flow.
views.py :
from snippets.models import Equipamento, Colaborador
from snippets.serializers import EquipamentoSerializer, ColaboradorSerializer
from rest_framework import mixins
from rest_framework import generics
class EquipamentoList(generics.ListCreateAPIView):
serializer_class = EquipamentoSerializer
def get_queryset(self):
queryset = Equipamento.objects.all()
id = self.request.query_params.get('id', None)
if id is not None:
queryset = queryset.filter(id=id)
return queryset
# class ColaboradorList(generics.CreateAPIView):
# queryset = Colaborador.objects.all()
# serializer_class = ColaboradorSerializer
# def get_queryset(self):
# queryset = Colaborador.objects.all()
# id = self.request.query_params.get('id', None)
# if id is not None:
# queryset = queryset.filter(pk=pk)
# return queryset
# def create(self, request, pk):
# queryset = Colaborador.objects.all()
# return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
# class ColaboradorDetail(generics.RetrieveUpdateDestroyAPIView):
# queryset = Colaborador.objects.all()
# serializer_class = ColaboradorSerializer
class ColaboradorList(mixins.ListModelMixin,
mixins.CreateModelMixin,
generics.GenericAPIView):
queryset = Colaborador.objects.all()
serializer_class = ColaboradorSerializer
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
return self.create(request, *args, **kwargs)
class ColaboradorDetail(mixins.RetrieveModelMixin,
mixins.UpdateModelMixin,
mixins.DestroyModelMixin,
generics.GenericAPIView):
queryset = Colaborador.objects.all()
serializer_class = ColaboradorSerializer
def get(self, request, *args, **kwargs):
return self.retrieve(request, *args, **kwargs)
def put(self, request, *args, **kwargs):
return self.update(request, *args, **kwargs)
def delete(self, request, *args, **kwargs):
return self.destroy(request, *args, **kwargs)
serializers.py
from rest_framework import serializers
from rest_framework.validators import UniqueValidator
from snippets.models import Equipamento, Colaborador, Propriedade, MotivoParada, Apontamento
class EquipamentoSerializer(serializers.Serializer):
id = serializers.IntegerField(read_only=True)
cod_equip = serializers.IntegerField(validators=[UniqueValidator(queryset=Equipamento.objects.all())])
desc_equip = serializers.CharField(allow_blank=True, max_length=15, required=False)
def restore_object(self, attrs, instance=None):
"""
Create or update a new snippet instance, given a dictionary
of deserialized field values.
Note that if we don't define this method, then deserializing
data will simply return a dictionary of items.
"""
if instance:
# Update existing instance
instance.id = attrs.get('id', instance.id)
instance.cod_equip = attrs.get('cod_equip', instance.cod_equip)
instance.des_equip = attrs.get('desc_equip', instance.desc_equip)
return instance
# Create new instance
return Equipamento(**attrs)
class ColaboradorSerializer(serializers.Serializer):
id = serializers.IntegerField(read_only=True)
cod_colab = serializers.IntegerField(validators=[UniqueValidator(queryset=Colaborador.objects.all())])
nome_colab = serializers.CharField(max_length=30)
def restore_object(self, attrs, instance=None):
"""
Create or update a new snippet instance, given a dictionary
of deserialized field values.
Note that if we don't define this method, then deserializing
data will simply return a dictionary of items.
"""
if instance:
# Update existing instance
instance.id = attrs.get('id', instance.id)
instance.cod_colab = attrs.get('cod_colab', instance.cod_colab)
instance.nome_colab = attrs.get('nome_colab', instance.nome_colab)
return instance
# Create new instance
return Colaborador(**attrs)
class ApontamentoSerializer(serializers.Serializer):
id = serializers.IntegerField(read_only=True)
criado = serializers.DateTimeField(read_only=True)
apont_inicio = serializers.TimeField()
apont_fim = serializers.TimeField()
duracao = serializers.TimeField()
equipamento = serializers.PrimaryKeyRelatedField(queryset=Equipamento.objects.all())
colaborador = serializers.PrimaryKeyRelatedField(queryset=Colaborador.objects.all())
propriedade = serializers.PrimaryKeyRelatedField(queryset=Propriedade.objects.all())
m_parada = serializers.PrimaryKeyRelatedField(queryset=MotivoParada.objects.all())
def restore_object(self, attrs, instance=None):
"""
Create or update a new snippet instance, given a dictionary
of deserialized field values.
Note that if we don't define this method, then deserializing
data will simply return a dictionary of items.
"""
if instance:
# Update existing instance
instance.id = attrs.get('id', instance.id)
instance.criado = attrs.get('criado', instance.criado)
instance.apont_inicio = attrs.get('apont_inicio', instance.apont_inicio)
instance.apont_fim = attrs.get('apont_fim', instance.apont_fim)
instance.duracao = attrs.get('duracao', instance.duracao)
instance.equipamento = attrs.get('equipamento', instance.equipamento)
instance.colaborador = attrs.get('colaborador', instance.colaborador)
instance.propriedade = attrs.get('propriedade', instance.propriedade)
instance.m_parada = attrs.get('m_parada', instance.m_parada)
return instance
# Create new instance
return Apontamento(**attrs)
class PropriedadeSerializer(serializers.Serializer):
id = serializers.IntegerField(read_only=True)
cod_prop = serializers.IntegerField(validators=[UniqueValidator(queryset=Propriedade.objects.all())])
desc_prop = serializers.CharField(max_length=30)
def restore_object(self, attrs, instance=None):
"""
Create or update a new snippet instance, given a dictionary
of deserialized field values.
Note that if we don't define this method, then deserializing
data will simply return a dictionary of items.
"""
if instance:
# Update existing instance
instance.id = attrs.get('id', instance.id)
instance.cod_prop = attrs.get('cod_prop', instance.cod_prop)
instance.des_prop = attrs.get('desc_prop', instance.desc_prop)
return instance
# Create new instance
return Propriedade(**attrs)
class MotivoParadaSerializer(serializers.Serializer):
id = serializers.IntegerField(read_only=True)
cod_mparada = serializers.IntegerField(validators=[UniqueValidator(queryset=MotivoParada.objects.all())])
desc_mparada = serializers.CharField(max_length=30)
def restore_object(self, attrs, instance=None):
"""
Create or update a new snippet instance, given a dictionary
of deserialized field values.
Note that if we don't define this method, then deserializing
data will simply return a dictionary of items.
"""
if instance:
# Update existing instance
instance.id = attrs.get('id', instance.id)
instance.cod_mparada = attrs.get('cod_mparada', instance.cod_mparada)
instance.des_mparada = attrs.get('desc_mparada', instance.desc_mparada)
return instance
# Create new instance
return MotivoParada(**attrs)
urls.py
from django.conf.urls import url
# from snippets.views import EquipamentoList, ColaboradorList, ColaboradorDetail
from snippets import views
from rest_framework.urlpatterns import format_suffix_patterns
urlpatterns = [
# url(r'^snippets/$', views.snippet_list),
# url(r'^snippets/(?P<pk>[0-9]+)/$', views.snippet_detail),
# url('^equipamento/(?P<id>.+)/$', EquipamentoList.as_view()),
#url('^colab/(?P<id>.+)/$', ColaboradorList.as_view()),
url('^colab/$', views.ColaboradorList.as_view()),
url('^colab_add/(?P<pk>[0-9]+)/$', views.ColaboradorDetail.as_view()),
]
urlpatterns = format_suffix_patterns(urlpatterns)I find message return in google, not find solv problem?
Help.
Whats my code not post values?
I need help for solution correct.
The error message is pretty straightforward. Your serializers use the restore_object method, which is deprecated in Rest Framework 3. Either downgrade your Django Rest Framework version to 2.x, or (recommended) rewrite your code to make it compatible with Rest Framework's latest version.