Original exception text was: 'QuerySet' object has no attribute 'customer_name' - python

Please check me this error with serializers.
I have two model Customer and Factor:
models.py:
class Customer(models.Model):
customer_name = models.CharField(max_length=120 ,verbose_name='بنام')
final_price = models.DecimalField(max_digits=20, decimal_places=0, default=0, verbose_name='مبلغ کل فاکتور')
def __str__(self):
return f'{self.customer_name}'
class Factor(models.Model):
title = models.CharField(max_length=120 ,verbose_name='صورتحساب')
name = models.ForeignKey(Customer,on_delete=models.CASCADE,verbose_name='بنام' ,related_name='factor_set')
description = models.CharField(max_length=200 ,verbose_name='شرح کالا')
price = models.DecimalField(max_digits=20, decimal_places=0, default=0.0,verbose_name='قیمت واحد')
count =models.DecimalField(max_digits=20,decimal_places=0, default=1,verbose_name='تعداد')
date = models.DateTimeField(default=datetime.datetime.now,null=True,verbose_name='تاریخ')
def __str__(self):
return f'{self.name}'
serializer.py:
class FactorModelSerializer(serializers.ModelSerializer):
name = serializers.StringRelatedField(many=True)
class Meta:
model = Factor
fields = '__all__'
class CustomerModelSerializer(serializers.ModelSerializer):
factor_set=FactorModelSerializer(many=True)
class Meta:
model = Customer
fields = '__all__'
views.py:
class GetAllData__(APIView):
def get(self,request):
query = Customer.objects.all()
serializer=CustomerModelSerializer(query)
return Response(serializer.data ,status=status.HTTP_200_OK)
urls.py :
from factor.views import GetAllData,GetAllData__
urlpatterns = [
path('get-all-data--', GetAllData__.as_view()),
]
error :
AttributeError at /get-all-data--
Got AttributeError when attempting to get a value for field customer_name on serializer CustomerModelSerializer.
The serializer field might be named incorrectly and not match any attribute or key on the QuerySet instance.
Original exception text was: 'QuerySet' object has no attribute 'customer_name'.

you need to provide source as 'factor_set' since Your serializer is searching from where to to put customer_name
class FactorModelSerializer(serializers.ModelSerializer):
name = serializers.StringRelatedField(many=True)
class Meta:
model = Factor
fields = '__all__'
class CustomerModelSerializer(serializers.ModelSerializer):
factor_set=FactorModelSerializer(many=True,source='factor_set')
class Meta:
model = Customer
fields = '__all__'

Related

"Got KeyError when attempting to get a value for field `fk_idbrand` on serializer

I'm currently building a django app and I'm serializing my views, but when applying the serializer to the model is experiencing an error that I've been unable to fix:
models.py
class vehicles_brand(models.Model):
pk_idbrand= models.AutoField(db_column='PK_IdBrand', primary_key=True) # Field name made lowercase.
fk_idcountry= models.ForeignKey(locations_country, on_delete= models.CASCADE, db_column='FK_IdLocationCountry', related_name='Country')
name = models.CharField(max_length=20, default=None, null=True)
class Meta:
db_table = 'vehicles_brand'
verbose_name_plural = "Vehicle Brands"
def __str__(self):
return self.name
class vehicles_model(models.Model):
pk_idmodel = models.AutoField(db_column='PK_IdModel', primary_key=True) # Field name made lowercase.
name = models.CharField(max_length=20, default=None)
fk_idbrand= models.ForeignKey(vehicles_brand, on_delete= models.CASCADE, db_column='FK_IdVehicleBrand', related_name='Brand')
class Meta:
db_table = 'vehicles_model'
verbose_name_plural = "Vehicle Models"
serializers.py
class brandSerializer(serializers.ModelSerializer):
class Meta:
model = vehicles_brand
fields = '__all__'
class modelSerializer(serializers.ModelSerializer):
brand = brandSerializer(source="FK_IdVehicleBrand", many=True, read_only=True)
class Meta:
model = vehicles_model
fields = '__all__'
output:
"Got KeyError when attempting to get a value for field `fk_idbrand` on serializer `modelSerializer`.\nThe serializer field might be named incorrectly and not match any attribute or key on the `dict` instance.\nOriginal exception text was: 'fk_idbrand'."
I've checked my models and the serializers but for me everything seems to be ok, thanks in advance for any hint or help.
class modelSerializer(serializers.ModelSerializer):
# actually It should be Brand which is related name in table
Brand = brandSerializer(source="FK_IdVehicleBrand",many=True,read_only=True)
class Meta:
model = vehicles_model
fields = '__all__'

AttributeError at /files/

when I am going to implement tag field I am getting following error
AttributeError: Got AttributeError when attempting to get a value for field tags on serializer CategorySerializers.
The serializer field might be named incorrectly and not match any attribute or key on the Category instance.
Original exception text was: 'Category' object has no attribute 'tags'.
models.py
class Category(models.Model):
name = models.CharField(max_length=100)
class Tag(models.Model):
tag_name = models.CharField(max_length=30)
class FileUp(models.Model):
name = models.ForeignKey(Category, on_delete=models.CASCADE)
file = models.FileField(upload_to='path')
tags = models.ManyToManyField(Tag)
def __str__(self):
return self.name.name
serializers.py
class TagSerializers(serializers.ModelSerializer):
class Meta:
model = Tag
fields = ['tag_name']
class FileSerializers(serializers.ModelSerializer):
class Meta:
model = FileUp
fields = ['file']
class CategorySerializers(serializers.HyperlinkedModelSerializer):
files = FileSerializers(source='file_set', many=True, read_only=True)
tags = TagSerializers(many=True)
class Meta:
model = Category
fields = ['id', 'name', 'files', 'tags']
read_only_fields = ['tags']
def create(self, validated_data):
files_data = self.context.get('view').request.FILES
name = Category.objects.create(name=validated_data.get('name'))
for file_data in files_data.values():
FileUp.objects.create(name=name, file=file_data)
return name
here is what I tried, I have put Tag in Category model but when I am going to add files I cannot add tags to it or select tags in the admin panel. But, If I add Tag to FileUp I am getting error above shown. How can I apply to Tag to FileUp? any help please?
Use SerializerMethodField parameter,
class CategorySerializers(serializers.HyperlinkedModelSerializer):
files = FileSerializers(source='file_set', many=True, read_only=True)
tags = serializers.SerializerMethodField()
def get_tags(self, category):
return TagSerializers(Tag.objects.filter(fileup__name__categories=category), many=True).data
class Meta:
model = Category
fields = ['id', 'name', 'files', 'tags']
read_only_fields = ['tags']

How to get child model having foregin key of parent model in Django rest framwork?

now i want output such a way that there for each list i must get entire timing record how to achieve it
below is my model
model.py
class Refreshment(models.Model):
title = models.CharField(max_length=200, unique=True)
charges = models.DecimalField(max_digits=12, decimal_places=2, help_text="Charges per hour")
class Timeing(models.Model):
refreshment = models.OneToOneField(Refreshment,on_delete=models.CASCADE)
sunday_open = models.TimeField(blank=True, editable=True)
Below is my views.py
#api_view()
def all_games_sports(request):
entertainment = Refreshment.objects.filter(type=1)
serialize = EntertainmentSerializer(instance=entertainment, many=True)
main = {'status': True, 'code': "CODE_SUCCESSFUL", 'msg': "SUCCESS", 'all_games_sports': serialize.data}
return Response(main)
Serializer.py
class TimeingSerializer(serializers.ModelSerializer):
class Meta:
model = Timeing
fields = '__all__'
class EntertainmentSerializer(serializers.ModelSerializer):
refreshment = TimeingSerializer(many=True,read_only=True)
class Meta:
model = Refreshment
fields = '__all__'
AttributeError: Got AttributeError when attempting to get a value for field `refreshment` on serializer `AvailableHourSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `Refreshment` instance.
Original exception text was: 'Refreshment' object has no attribute 'refreshment'.
Your code throws an error. It should. You defined refreshment, but not added it to fields.
class EntertainmentSerializer(serializers.ModelSerializer):
refreshment = TimeingSerializer(many=True,read_only=True)
class Meta:
model = Refreshment
fields = '__all__' #You have not added refreshment to fields.
You should be doing this instead:
class EntertainmentSerializer(serializers.ModelSerializer):
timeing = TimeingSerializer(many=True,read_only=True)
class Meta:
model = Refreshment
fields = '__all__'

Django Attribute error on serializer when using intermediate model

I've been trying to create a serializer for a Model in which one of the fields is a ManytoManyField through a Model that adds more fields. The problem is that the intermediate serializer is not recognizing that has added fields. Why could I be doing wrong?
Here is my code:
models.py:
class Product(models.Model):
name = models.CharField(max_length=30, unique=True)
class Movement(models.Model):
date = models.DateTimeField(auto_now_add=True)
products = models.ManyToManyField(Product, through='Movement_Product')
class Movement_Product(models.Model):
movement = models.ForeignKey(Movement)
product = models.ForeignKey(Product)
amount = models.IntegerField()
price = models.DecimalField(max_digits=9, decimal_places=2)
class Input(Movement):
invoice_number = models.CharField(max_length=30, null=True)
serializers.py:
class ProductSerializer(serializers.ModelSerializer):
class Meta:
model = Product
class MovementProductSerializer(serializers.ModelSerializer):
product = ProductSerializer()
price = serializers.DecimalField(max_digits=9, decimal_places=2)
amount = serializers.IntegerField()
class Meta:
model = Movement_Product
class InputSerializer(serializers.ModelSerializer):
date = serializers.DateTimeField()
products = MovementProductSerializer(many=True)
class Meta:
model = Input
views.py:
class InputViewSet(viewsets.ModelViewSet):
queryset = Input.objects.order_by('-date')
serializer_class = InputSerializer
urls.py:
router = routers.DefaultRouter()
router.register(r'input', views.InputViewSet)
urlpatterns = [
url(r'^api/', include(router.urls)),
url(r'^admin/', admin.site.urls),
]
The error I got when I try to render the InputSerializer on URL path in my browser http://127.0.0.1:8000/api/input/:
Attribute Error at /api/input/
Got AttributeError when attempting to get a value for field product on serializer MovementProductSerializer.
The serializer field might be named incorrectly and not match any attribute or key on the Product instance.
Original exception text was: 'Product' object has no attribute 'product'.
try this:
class Movement(models.Model):
date = models.DateTimeField(auto_now_add=True)
products = models.ManyToManyField(Product, through='Movement_Product')
#property
def movement_product(self):
return Movement_Product.objects.filter(movement=self)
class InputSerializer(serializers.ModelSerializer):
date = serializers.DateTimeField()
products = serializers.ListField(child=MovementProductSerializer(), source='movement_product')
class Meta:
model = Input

Attribute Error after adding many=True in restframework django?

class CommentSerializer(serializers.ModelSerializer):
class Meta:
model = Comment
fields=('Comment','Comment_text','Comment_time','Comment_Post','Comment_User', )
class PostSerializers(serializers.ModelSerializer):
comment = CommentSerializer(many=True)
class Meta:
model = Postovo
fields = ('Postovo_id','Postovo_trending','comment', )
Models are like this
class Postovo(models.Model):
Postovo_id = models.AutoField(primary_key=True)
Postovo_type = models.ForeignKey(Type, related_name='posttype' ,default='1', editable=True)
Postovo_time = models.CharField(max_length=100,default=currentTimestamp, editable=True)
Postovo_link1 = models.CharField(max_length=1000,default='linkofimage1', editable=True)
Postovo_link2 = models.CharField(max_length=1000,default='linkofimage2', editable=True)
Postovo_person1=models.CharField(max_length=100,default='person1', editable=True)
Postovo_person2=models.CharField(max_length=100,default='person2', editable=True)
Postovo_hot=models.CharField(max_length=100,default='False', editable=True)
Postovo_trending=models.CharField(max_length=100,default='False', editable=True)
def __str__(self):
return '%s' % (self.Postovo_id)
Next
class Comment(models.Model):
Comment = models.AutoField(primary_key=True)
Comment_text = models.CharField(max_length=100)
Comment_time = models.CharField(max_length=100,default=currentTimestamp)
Comment_Post = models.ForeignKey(Postovo, related_name='commentpost' ,default='1', editable=True)
Comment_User = models.ForeignKey(RegUser, related_name='commentuser' ,default='1', editable=True)
def __str__(self):
return '%s' % (self.Comment)
In views
class Postcomment(viewsets.ModelViewSet):
queryset = Postovo.objects.all()
serializer_class = PostSerializers
ERROR
AttributeError: Got AttributeError when attempting to get a value for
field comment on serializer PostSerializers. The serializer field
might be named incorrectly and not match any attribute or key on the
Postovo instance. Original exception text was: 'Postovo' object has
no attribute 'comment'.
You need to use the related name commentpost instead of comment in PostSerializers.
class PostSerializers(serializers.ModelSerializer):
commentpost = CommentSerializer(many=True)
class Meta:
model = Postovo
fields = ('Postovo_id','Postovo_trending','commentpost', )
The error is coming because there is no comment attribute on a Postovo instance. The manager for getting all the related Comment instances is accessible using the related_name commentpost.

Categories