MU
Maciej UrmańskiDec. 11, 2019, 6:27 a.m.

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:

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

We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

7
Evgenii Legotckoi
  • Dec. 11, 2019, 6:52 a.m.

Hello,

Try this

from django.db.models import Count
embeds = Embed.objects.annotate(total=Count('added_by'))
embeds[0].total
    MU
    • Dec. 11, 2019, 7:52 a.m.
    • (edited)

    Hmm this count every recipes. Not only one user.

    I try something like that from stackoverflow:

    def recipedetail(request, slug):
        recipe = get_object_or_404(Embed, slug=slug)
        num_embed = recipe.objects.filter(added_by=added_by).count()
        return render(request, 'recipes/detail.html', {'recipe': recipe,
                                                        '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
      • Dec. 11, 2019, 8:07 a.m.
      • (edited)

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

      And in this code you get object of model

      recipe = get_object_or_404(Embed, slug=slug)
      

      Therefore you cannot use objects in this row

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

      Because of objects can be used only in this situation

      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

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

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

        MU
        • Dec. 11, 2019, 8:08 a.m.

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

          Evgenii Legotckoi
          • Dec. 11, 2019, 8:11 a.m.
          • (edited)

          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

          def recipedetail(request, slug):
              recipe = get_object_or_404(Embed, slug=slug)
              num_embed = recipe.objects.filter(added_by=request.user).count()
              return render(request, 'recipes/detail.html', {'recipe': recipe,
                                                              'num_embed': num_embed}
          
            Evgenii Legotckoi
            • Dec. 11, 2019, 8:14 a.m.

            or this

            def recipedetail(request, slug):
                recipe = get_object_or_404(Embed, slug=slug)
                num_embed = recipe.objects.filter(added_by=recipe.added_by).count()
                return render(request, 'recipes/detail.html', {'recipe': recipe,
                                                                'num_embed': num_embed}
            
              MU
              • Dec. 11, 2019, 8:27 a.m.
              • The answer was marked as a solution.

              Thank you! Now works, and this is solution.

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

                Comments

                Only authorized users can post comments.
                Please, Log in or Sign up
                AD

                C ++ - Test 004. Pointers, Arrays and Loops

                • Result:50points,
                • Rating points-4
                m

                C ++ - Test 004. Pointers, Arrays and Loops

                • Result:80points,
                • Rating points4
                m

                C ++ - Test 004. Pointers, Arrays and Loops

                • Result:20points,
                • Rating points-10
                Last comments
                i
                innorwallNov. 14, 2024, 9:26 p.m.
                Qt/C++ - Lesson 031. QCustomPlot – The build of charts with time buy generic priligy We can just chat, and we will not lose too much time anyway
                i
                innorwallNov. 14, 2024, 7:03 p.m.
                Qt/C++ - Lesson 060. Configuring the appearance of the application in runtime I didnt have an issue work colors priligy dapoxetine 60mg revia cost uk August 3, 2022 Reply
                i
                innorwallNov. 14, 2024, 12:07 p.m.
                Circuit switching and packet data transmission networks Angioedema 1 priligy dapoxetine
                i
                innorwallNov. 14, 2024, 11:42 a.m.
                How to Copy Files in Linux If only females relatives with DZ offspring were considered these percentages were 23 order priligy online uk
                i
                innorwallNov. 14, 2024, 9:09 a.m.
                Qt/C++ - Tutorial 068. Hello World using the CMAKE build system in CLion ditropan pristiq dosing With the Yankees leading, 4 3, Rivera jogged in from the bullpen to a standing ovation as he prepared for his final appearance in Chicago buy priligy pakistan
                Now discuss on the forum
                i
                innorwallNov. 14, 2024, 3:39 a.m.
                добавить qlineseries в функции priligy amazon canada 93 GREB1 protein GREB1 AB011147 6
                i
                innorwallNov. 11, 2024, 10:55 a.m.
                Всё ещё разбираюсь с кешем. priligy walgreens levitra dulcolax carbs The third ring was found to be made up of ultra relativistic electrons, which are also present in both the outer and inner rings
                9
                9AnonimOct. 25, 2024, 9:10 a.m.
                Машина тьюринга // Начальное состояние 0 0, ,<,1 // Переход в состояние 1 при пустом символе 0,0,>,0 // Остаемся в состоянии 0, двигаясь вправо при встрече 0 0,1,>…

                Follow us in social networks