MU
11 декабря 2019 г. 17:27

Count user objects e.g posts

python, Django

Hi, I try to get numbers of user post.

I have model Embed and try to count how many user add this embeds.

My model:

  1. class Embed(models.Model):
  2. url = models.URLField(max_length=255)
  3. title = models.CharField(max_length=255, verbose_name='Tytuł')
  4. description = HTMLField(verbose_name='Opis', blank=True, null=True)
  5. type = models.CharField(blank=True, max_length=200)
  6. thumbnail_url = models.URLField(max_length=255, blank=True, null=True)
  7. image = models.ImageField(upload_to='recipes', blank=True)
  8. html = models.TextField()
  9. votes = GenericRelation(LikeDislike, related_query_name='embedlikes')
  10. added_by = models.ForeignKey(User, on_delete=models.CASCADE)
  11. created_at = models.DateTimeField(auto_now_add=True)
  12. category = TreeManyToManyField(RecipeCategory, blank=True, null=True, related_name='embeds', verbose_name='Kategoria')
  13. slug = AutoSlugField(populate_from='title', unique=True)
  14.  
2

Вам это нравится? Поделитесь в социальных сетях!

7
Evgenii Legotckoi
  • 11 декабря 2019 г. 17:52

Hello,

Try this

  1. from django.db.models import Count
  2. embeds = Embed.objects.annotate(total=Count('added_by'))
  3. embeds[0].total
    MU
    • 11 декабря 2019 г. 18:52
    • (ред.)

    Hmm this count every recipes. Not only one user.

    I try something like that from stackoverflow:

    1. def recipedetail(request, slug):
    2. recipe = get_object_or_404(Embed, slug=slug)
    3. num_embed = recipe.objects.filter(added_by=added_by).count()
    4. return render(request, 'recipes/detail.html', {'recipe': recipe,
    5. 'num_embed': num_embed}

    But then error appear:

    Manager isn't accessible via Embed instances

    I have this from there: https://stackoverflow.com/questions/50393455/count-the-number-of-posts-by-a-user-django

      Evgenii Legotckoi
      • 11 декабря 2019 г. 19:07
      • (ред.)

      May be, because, you don`t have field "author" in your model... ?

      And in this code you get object of model

      1. recipe = get_object_or_404(Embed, slug=slug)

      Therefore you cannot use objects in this row

      1. num_embed = recipe.objects.filter(author=author).count()

      Because of objects can be used only in this situation

      1. Embed.objects.all() # only for model class, not for instance

      And I don`t see author instance in your code.

      You can write something else like this

      1. def recipedetail(request, slug):
      2. recipe = get_object_or_404(Embed, slug=slug)
      3. # missed author instance, need to add code for getting author instance
      4. num_embed = Embed.objects.filter(added_by=author).count()
      5. return render(request, 'recipes/detail.html', {'recipe': recipe,
      6. 'num_embed': num_embed}

      But you should get author instance from anywhere, for example request.user

        MU
        • 11 декабря 2019 г. 19:08

        Yeah I edit my answer and change to added_by. But still this don't work.

          Evgenii Legotckoi
          • 11 декабря 2019 г. 19:11
          • (ред.)

          added_by must be some author instance, some object. You should get this object from anywhere. In your code you don`t make any actions for getting author instance.

          Ok, try this

          1. def recipedetail(request, slug):
          2. recipe = get_object_or_404(Embed, slug=slug)
          3. num_embed = recipe.objects.filter(added_by=request.user).count()
          4. return render(request, 'recipes/detail.html', {'recipe': recipe,
          5. 'num_embed': num_embed}
            Evgenii Legotckoi
            • 11 декабря 2019 г. 19:14

            or this

            1. def recipedetail(request, slug):
            2. recipe = get_object_or_404(Embed, slug=slug)
            3. num_embed = recipe.objects.filter(added_by=recipe.added_by).count()
            4. return render(request, 'recipes/detail.html', {'recipe': recipe,
            5. 'num_embed': num_embed}
              MU
              • 11 декабря 2019 г. 19:27
              • Ответ был помечен как решение.

              Thank you! Now works, and this is solution.

              1. num_embed = Embed.objects.filter(added_by=recipe.added_by).count()

                Комментарии

                Только авторизованные пользователи могут публиковать комментарии.
                Пожалуйста, авторизуйтесь или зарегистрируйтесь