Attribute Error after adding many=True in restframework django? - python

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.

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

count total object in foreign key - drf

i want to count comments for every single Post
in models.py:
class Post(models.Model):
body = models.TextField(max_length=10000)
date = models.DateTimeField(auto_now_add=True, blank=True)
user = models.ForeignKey(User, on_delete=models.CASCADE)
liked_by = models.ManyToManyField(User, blank=True, related_name='liked_by')
class Meta:
ordering = ['-date']
class Comment(models.Model):
body = models.TextField(max_length=1000)
date = models.DateTimeField(auto_now_add=True, blank=True)
user = models.ForeignKey(User, on_delete=models.CASCADE)
post = models.ForeignKey(Post, on_delete=models.CASCADE)
class Meta:
ordering = ['-date']
in serializers.py:
class CommentSerializer(serializers.ModelSerializer):
class Meta:
model = Comment
fields = '__all__'
class PostSerializer(serializers.ModelSerializer):
#comments = CommentSerializer()
user = UserSerializers()
total_likes = serializers.SerializerMethodField()
liked_by = SimpleUserSerializer(many=True, read_only=True)
total_comments = serializers.SerializerMethodField()
class Meta:
model = Post
fields = ('body','date','user', 'total_likes', 'liked_by','total_comments')
def get_total_likes(self, instance):
return instance.liked_by.count()
def get_total_comments(self, instance):
return instance.comments.count()
when i run this code, it shows, AttributeError: 'Post' object has no attribute 'comments'.
how do i count comments of a post?
Since you haven't configured the related_name, Django uses the default related_name and hence you should access the reveres FK using comment_set instead of comments
Thus, the get_total_comments(...) method should look like
def get_total_comments(self, instance):
return instance.comment_set.count()
Reference
What is related_name used for in Django?

'Slide' object has no attribute 'topicdetail_set'

I created a model for Slide on django. below is model.py
class Slide(models.Model):
user = models.ForeignKey(User, on_delete=models.DO_NOTHING, blank=True)
text = models.CharField(max_length=300)
is_deleted = models.BooleanField(default=False)
topic_id = models.ForeignKey(Article, on_delete=models.DO_NOTHING)
created_at = models.DateTimeField("created at", auto_now_add=True)
objects = models.Manager()
def __str__(self):
return self.text
serializer.py
class SlideSerializer(serializers.ModelSerializer):
topicdetail_set = ArticleDetailSerial(many=True)
user_detail = FindOwnerSerializer(source='user', read_only=True)
author = AuthorSerializer(many=True)
class Meta:
model = Slide
fields = ('id','text', 'created_at', 'topicdetail_set', 'user_detail','author')
When I run the url for slide http://127.0.0.1:8000/article/slide/
then I got below error
AttributeError: Got AttributeError when attempting to get a value for field `topicdetail_set` on serializer `SlideSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `Slide` instance.
Original exception text was: 'Slide' object has no attribute 'topicdetail_set'.
Now I am confused, Is the code that I have created is wrong? And if it is wrong then how should I fix it?

AttributeError: 'AttributeValueAdmin' object has no attribute 'urls'

I have designed a table for attribute and product attributes. An attribute can have many values.
For example, an attribute called color can have values like Black, white, Grey, Maroon etc. For
this I designed a table such way
However when registering to the admin, I get AttributeError: 'AttributeValueAdmin' object has no attribute 'urls' error.
class Attribute(models.Model):
name = models.CharField(max_length=30, unique=True)
slug = models.SlugField(max_length=250, unique=True)
class Meta:
verbose_name = "Attribute"
verbose_name_plural = "Attributes"
def __str__(self):
return self.name
class ProductAttribute(SortableModel):
product = models.ForeignKey(Product,
related_name="productattribute",
null=True,
on_delete=models.CASCADE)
attribute = models.ManyToManyField(
Attribute,
through="AttributeValue"
)
class Meta:
ordering = ("sort_order",)
verbose_name = "Product Attribute"
verbose_name_plural = "Product Attributes"
class AttributeValue(SortableModel):
name = models.CharField(max_length=250)
value = models.CharField(max_length=100, blank=True, default="")
slug = models.SlugField(max_length=255)
productattribute = models.ForeignKey(ProductAttribute,
null=True,
related_name='productattribute',
on_delete=models.CASCADE)
attribute = models.ForeignKey(
Attribute, related_name="values", on_delete=models.CASCADE
)
class Meta:
ordering = ("sort_order", "id")
unique_together = ("slug", "attribute")
def __str__(self) -> str:
return self.name
admin.py
class ProductAdmin(admin.ModelAdmin):
model = models.Product
prepopulated_fields = {'slug': ('name',), }
class AttributeValueAdmin(admin.TabularInline):
model = models.AttributeValue
extra = 2
class AttributeAdmin(admin.ModelAdmin):
model = models.Attribute
prepopulated_fields = {'slug': ('name',), }
class ProductAttributeAdmin(admin.ModelAdmin):
# model = models.ProductAttribute
inlines = (AttributeValueAdmin, )
admin.site.register(models.Attribute, AttributeAdmin)
admin.site.register(models.AttributeValue, AttributeValueAdmin)
admin.site.register(models.ProductAttribute, ProductAttributeAdmin)
As per django docs on admin, the first step is to display the intermediate model by subclassing inline class for AttributeValue table like you have done
class AttributeValueInline(admin.TabularInline):
model = models.AttributeValue
extra = 2
Second step is to create admin views for both Attribute and ProductAttribute models.
class AttributeAdmin(admin.ModelAdmin):
inlines = (AttributeValueInline, )
prepopulated_fields = {'slug': ('name',), }
class ProductAttributeAdmin(admin.ModelAdmin):
inlines = (AttributeValueInline, )
Third step is to register your Attribute and ProductAttribute models
admin.site.register(models.Attribute, AttributeAdmin)
admin.site.register(models.ProductAttribute, ProductAttributeAdmin)
You don't need to register AttributeValue model as you can create/edit AttributeValue inline from either Attribute or ProductAttribute table.
For reference you can read the django docs
https://docs.djangoproject.com/en/3.0/ref/contrib/admin/#working-with-many-to-many-intermediary-models

AttributeError with Django REST Framework and a ManyToMany relationship

Trying to access my json page I get this error!
AttributeError at /project/api/1.json
Got AttributeError when attempting to get a value for field `title` on serializer `TaskSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `RelatedManager` instance.
Original exception text was: 'RelatedManager' object has no attribute 'title'.
I have a Many to Many relationship with my models:
class Project(models.Model):
owner = models.ForeignKey('auth.User')
title = models.CharField(max_length=100)
slug = models.SlugField(unique=True)
created_date = models.DateTimeField(auto_now_add=True, auto_now=False)
updated_date = models.DateTimeField(auto_now_add=False, auto_now=True)
def __str__(self):
return self.title
def save(self, **kwargs):
super(Project, self, **kwargs).save()
self.slug = slugify(self.title)
super(Project, self, **kwargs).save()
def create(self):
pass
class Task(models.Model):
title = models.CharField(max_length=100)
description = models.TextField(blank=True)
completed = models.BooleanField(default=False)
project = models.ForeignKey('Project', related_name="tasks")
dependency = models.ManyToManyField('self', through='Dependency', null=True,
blank=True, through_fields=('task', 'sub_task'), symmetrical=False)
def sub_tasks(self, **kwargs):
qs = self.dependency.filter(**kwargs)
for sub_task in qs:
qs = qs | sub_task.sub_tasks(**kwargs)
return qs
def __str__(self):
return self.title
class Dependency(models.Model):
task = models.ForeignKey(Task, related_name="dependency_task")
sub_task = models.ForeignKey(Task, related_name="dependency_sub_task")
And these serializers:
class TaskSerializer(serializers.ModelSerializer):
class Meta:
model = Task
fields = ('id', 'title', 'project', 'completed',)
class ProjectSerializer(serializers.ModelSerializer):
tasks = TaskSerializer()
class Meta:
model = Project
fields = ('id', 'title', 'tasks',)
How can I get round this? RelatedManager tells me something is disagreeing with my M2M link, but why/how? I couldn't see anything here about Attribute Errors.
This question seems related, but setting many=False doesn't do anything.
AttributeError with Django REST Framework and MongoEngine
In that question they set many=False. You do have a Many-to-Many, so set many=True It's that simple.
In fact if you look closely, that's how the example shows you to do it:
class TrackListingField(serializers.RelatedField):
def to_representation(self, value):
duration = time.strftime('%M:%S', time.gmtime(value.duration))
return 'Track %d: %s (%s)' % (value.order, value.name, duration)
class AlbumSerializer(serializers.ModelSerializer):
tracks = TrackListingField(many=True)
class Meta:
model = Album
fields = ('album_name', 'artist', 'tracks')
See how the tracks listing field has the many=True attribute? Do that.
I had a similar issue when I missed out on specifying the related_name attribute to the definition of ForeignKeyField pointing to the Album model.

Categories