Home > Enterprise >  How to get IntegerField from ForegienKey for objects model
How to get IntegerField from ForegienKey for objects model

Time:05-04

I have a profile, and in this profile I want to display bookmarks for all messages (this is my IntegerField). In other words, how many people have bookmarked a particular author's posts.

models.py

class Post(models.Model):
    slug = models.SlugField(unique=True)
    title = models.CharField(max_length=255, db_index=True)
    author = models.ForeignKey(
        "users.CustomUser", on_delete=models.SET_NULL, null=True, db_index=True
    )
    bookmarkscount = models.IntegerField(null=True, blank=True, default=0)

class Profile(models.Model):
   user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE)

This is my try in template but it does not work

<p>Bookmark</p>
<p>{{posts.bookmarkscount}}</p>

But work only if I use "for"

{% for post in posts %}
<p>{{ post.bookmarkscount}}</p>
 {% endfor %}

views.py

class ProfileDetailView(DetailView):
    model = Profile
    template_name = "users/profile/profile.html"


    def get_context_data(self, **kwargs):
        try:
            context["posts"] = Post.objects.filter(
                author=self.object.user.is_authenticated
            )
        except Post.DoesNotExist:
            context["posts"] = None

CodePudding user response:

posts is a QuerySet type, a representation of the query to be sent to the DB. More like a list on steroids rather than a single instance of Post. This is a crucial concept you need to understand before coding anything in Django. (Docs here)

In order to get a sum of all the bookmarkscount values from all posts of a user, you need to use aggregation. (Docs here)

from django.db.models import Sum

posts.aggregate(Sum('bookmarkscount'))
# returns i.e.: {'bookmarkscount': 234}
  • Related