AttributeError at /files/ - python

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']

Related

NameError: name 'Class' is not defined, How to access in a class it same name in Django?

models.py file that contain the Category model with name, description parent_category fields
class Category(models.Model):
""" Categories representation model """
name = models.CharField(max_length=50)
description = models.TextField()
parent_category = models.ForeignKey('self', on_delete=models.SET_NULL, null=True, blank=True)
serializers.py file, that container the Category model serializer with all it fields
class CategorySerializer(serializers.ModelSerializer):
""" product categories model serializer """
parent_category = CategorySerializer()
class Meta:
""" profile model serializer Meta class """
model = Category
fields = (
'id',
'name',
'description',
'parent_category'
)
views.py file, API view to get all available categories with required user authentication
class GetCategoriesView(APIView):
""" product categories getting view """
permission_classes = (IsAuthenticated,)
def get(self, request, *args, **kwargs):
""" get request method """
categories = Category.objects.all()
serializer = CategorySerializer(categories, many=True, context={'request':request})
return Response(data=serializer.data, status=HTTP_200_OK)
Expectected result, Json result with a recursive data from the parent_category field
{
name:'boy shoes',
description:'boy shoes category description'
parent_category:{
name:'shoes',
description:'shoes category description',
parent_category:{
name:'clothes',
description:'clothes category description',
parent_category: null
}
}
}
Error i get, i noticed that i can't access directly the Class inside the same class
NameError: name 'CategorySerializer' is not defined
How can i solve that?, i think you can help solve that issue
Thank you for your attention :)
You can't use same class as class variable. Just for info
class SomeClass:
x = SomeClass() # won't work NameError: name 'SomeClass' is not defined
def __init__(self):
x = SomeClass() # this is OK
So you have to change your serializer to something like this
class CategorySerializer(serializers.ModelSerializer):
""" product categories model serializer """
class Meta:
""" profile model serializer Meta class """
model = Category
fields = (
'id',
'name',
'description',
'parent_category'
)
def get_fields(self):
fields = super().get_fields()
fields['parent_category'] = CategorySerializer()
return fields

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

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__'

How to make a ManyToMany serialization to be able to create a object in the POST request?

I'm trying to create a serialize to handle a ManyToMany relation, but it's not working. I have read the documentation and I probably doing something wrong. Also I have read the answers here.
Here are my models.
class Author(models.Model):
name = models.CharField(verbose_name="Name", max_length=255)
class Book(models.Model):
author = models.ForeignKey(
Author,
related_name="id_author",
blank=True,
null=True,
on_delete=models.PROTECT)
price = models.FloatField(verbose_name="Price")
class FiscalDocument(models.Model):
seller = models.ForeignKey(
User,
related_name="user_id",
on_delete=models.PROTECT)
book = models.ManyToManyField(Book)
My serializer:
class AuthorSerializer(serializers.ModelSerializer):
class Meta:
model = Author
fields = ('id', 'name')
class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = ('id', 'author', 'price')
def to_representation(self, instance):
response = super().to_representation(instance)
response['author'] = AuthorSerializer(instance.author).data
return response
class FiscalDocumentSerializer(serializers.ModelSerializer):
book = BookSerializer()
class Meta:
model = FiscalDocument
fields = ('id', 'seller', 'book')
def create(self, validated_data):
book_data = validated_data.pop('book')
fiscal_document = FiscalDocument.objects.create(**validated_data)
Book.objects.create(FiscalDocument=FiscalDocument,**medicine_data)
return fiscal_document
When I try to access the endpoint of the FiscalDocument, django-rest-framework is throwing an error:
Got AttributeError when attempting to get a value for field price on serializer BookSerializer. The serializer field might be named incorrectly and not match any attribute or key on the ManyRelatedManager instance. Original exception text was: ManyRelatedManager object has no attribute price.
If anyone can help XD.

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__'

How to get an extra column in relational model in Django-rest-framework serializer?

I have Category and Article model,Article has a foreign key reference Category,in my serializer i can get the name column in Category model because of the __str__ method,but how can i get other columns in Category model
models.py:
# blog category models
class Category(models.Model):
#id = models.IntegerField(primary_key=True,help_text='primary key',auto_created=True)
name = models.CharField(max_length=50,help_text='category name')
description = models.TextField(default='',help_text='category description')
coverimg = models.CharField(max_length=200,default='',help_text='category front cover image')
covercolor = models.CharField(max_length=7,default='#ffffff',help_text='color for each category background')
totalitems = models.IntegerField(default=0,help_text='total items for each category')
createtime = models.DateTimeField(auto_now_add=True)
modifytime = models.DateTimeField(auto_now=True)
categories = models.Manager()
class Meta:
db_table = 'article_category'
def __str__(self):
return self.name
#blog article models
class Article(models.Model):
STATUS = (
(0,'on'),
(1,'off')
)
#id = models.IntegerField(primary_key=True,help_text='primary key',auto_created=True)
category = models.ForeignKey(Category,related_name='articles', help_text='foreigner key reference Category')
#author = models.ForeignKey(myadmin.User, help_text='foreigner key reference myadmin User')
title = models.CharField(max_length=100, help_text='article title')
description = models.TextField(help_text='article brief description')
content = models.TextField(help_text='article content')
like = models.IntegerField(default=0,help_text='like numbers')
secretcode = models.CharField(max_length=512,help_text='who has the code can scan')
status = models.IntegerField(choices=STATUS,help_text='status of the article')
createtime = models.DateTimeField(auto_now_add=True,help_text='time that first created')
modifytime = models.DateTimeField(auto_now=True,help_text='time when modified')
articles = models.Manager()
def __str__(self):
return self.title
class Meta:
db_table = 'article'
def save(self, *args, **kwargs):
if not self.id:
Category.categories.filter(pk=self.category.pk).update(totalitems = F('totalitems')+1)
super(Article,self).save(*args, **kwargs)
serializers.py:
# Article catalog
class ArticleCatalogSerializer(serializers.ModelSerializer):
category = serializers.StringRelatedField()
articletags = serializers.StringRelatedField(many=True)
covercolor = serializers.StringRelatedField()
class Meta:
model = Article
fields = ('id', 'title', 'category', 'articletags', 'description', 'like', 'createtime', 'covercolor')
covercolor = serializers.StringRelatedField() would cause an error:Article' object has no attribute 'covercolor and i changed to this :
changed serializers.py:
# category serializer for ArticleCatalogSerializer for nested relationship
class CategoryNestedRelationshipSerializer(serializers.ModelSerializer):
class Meta:
model = Category
fields = ('covercolor',)
# Article catalog
class ArticleCatalogSerializer(serializers.ModelSerializer):
category = serializers.StringRelatedField()
articletags = serializers.StringRelatedField(many=True)
covercolor = CategoryNestedRelationshipSerializer(read_only=True)
class Meta:
model = Article
ields = ('id', 'title', 'category', 'articletags', 'description', 'like', 'createtime', 'covercolor')
got an error:
Got AttributeError when attempting to get a value for field `covercolor` on serializer `ArticleCatalogSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `Article` instance.
Original exception text was: 'Article' object has no attribute 'covercolor'.
how to implement this ?
In your edit , Change your ArticleCatalogSerializer to
class ArticleCatalogSerializer(serializers.ModelSerializer):
category = CategoryNestedRelationshipSerializer()
class Meta:
model = Article
you will get output in this format
{
"id": 1,
"category": {
"covercolor": "#ffffff"
},
"title": "sa",
"description": "bhjghj",
"content": "sda",
"like": 0,
"secretcode": "77",
"status": 0,
"createtime": "2015-04-18T07:52:57.230110Z",
"modifytime": "2015-04-18T07:52:57.230135Z"
}
If you want any other column of category , you can include in your category serializer like this
class CategoryNestedRelationshipSerializer(serializers.ModelSerializer):
class Meta:
model = Category
fields = ('covercolor','name','description')
The StringRelatedField will emit the string representation of the related field.
To keep the 'flat' format you'll need to write a custom Field.
Alternatively if you want to include some reference to the Category, you'd want a PrimaryKeyRelatedField or nest the related model.

Categories