Home > Enterprise >  How to check for a specific attribute of the object referenced by foreign key in Django
How to check for a specific attribute of the object referenced by foreign key in Django

Time:09-18

Newbie here, forgive me if it's an easily solveable question.

So, I have a UserProfile model(one to one field related to base user) and posts and comments model.

Both posts and comments are related to their author by a foreign key. Both posts and comments have rating attribute(Int). For this example I'll talk about comments. My question is, how do I get all comment objects related to user by foreign key, and is it possible to not retrieve all comments themselves, but to retrieve only their rating values?

My UserProfile model looks like this

class UserProfile(models.Model):
    user = models.OneToOneField(
        User,
        on_delete=models.CASCADE,
        primary_key=True,
    )
    birthdate = models.DateField
    post_rating = models.IntegerField(default=0)
    comment_rating = models.IntegerField(default=0)

    def update_post_rating(self):
        pass

    def update_comment_rating(self):
        pass

My Comment model looks like this

class Comment(models.Model):
    author = models.ForeignKey(User, on_delete=models.SET('DELETED'))
    post = models.ForeignKey(Post, on_delete=models.CASCADE)
    rating = models.IntegerField(default=0)
    content = models.TextField
    date = models.DateField(auto_now_add=True)

    def like(self):
        self.rating =   1
        self.save()

    def dislike(self):
        self.rating = - 1
        self.save()

CodePudding user response:

I suppose you can write something like that :

class UserProfile(models.Model):
    user = models.OneToOneField(
        User,
        on_delete=models.CASCADE,
        primary_key=True,
    )
    birthdate = models.DateField
    post_rating = models.IntegerField(default=0)
    comment_rating = models.IntegerField(default=0)

    def update_post_rating(self):
        pass

    def update_comment_rating(self):
        related_comments = Comment.objects.filter(author=self.user)
        ratings = list(related_comments.values_list('rating', flat=True))
        avg_rating = sum(rating) / len(rating)
        self.comment_rating = avg_rating
        self.save()

I supposed the comment_rating is the average of all comment rating attached to this user ? You can also use the Avg annotation with queryset: https://docs.djangoproject.com/fr/4.1/topics/db/aggregation/

  • Related