MU
Maciej UrmańskiDec. 11, 2019, 5:27 p.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, 5:52 p.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, 6:52 p.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, 7:07 p.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, 7:08 p.m.

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

          Evgenii Legotckoi
          • Dec. 11, 2019, 7:11 p.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, 7:14 p.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, 7:27 p.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
                Ua

                Qt - Test 001. Signals and slots

                • Result:84points,
                • Rating points4
                Ua

                Qt - Test 001. Signals and slots

                • Result:42points,
                • Rating points-8
                ОК

                Qt - Test 001. Signals and slots

                • Result:47points,
                • Rating points-6
                Last comments
                ИМ
                Игорь МаксимовNov. 22, 2024, 9:51 p.m.
                Django - Tutorial 017. Customize the login page to Django Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
                Evgenii Legotckoi
                Evgenii LegotckoiOct. 31, 2024, 11:37 p.m.
                Django - Lesson 064. How to write a Python Markdown extension Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
                A
                ALO1ZEOct. 19, 2024, 5:19 p.m.
                Fb3 file reader on Qt Creator Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html
                ИМ
                Игорь МаксимовOct. 5, 2024, 4:51 p.m.
                Django - Lesson 064. How to write a Python Markdown extension Приветствую Евгений! У меня вопрос. Можно ли вставлять свои классы в разметку редактора markdown? Допустим имея стандартную разметку: <ul> <li></li> <li></l…
                d
                dblas5July 5, 2024, 8:02 p.m.
                QML - Lesson 016. SQLite database and the working with it in QML Qt Здравствуйте, возникает такая проблема (я новичок): ApplicationWindow неизвестный элемент. (М300) для TextField и Button аналогично. Могу предположить, что из-за более новой верси…
                Now discuss on the forum
                f
                firstlunoxodFeb. 15, 2025, 1:46 p.m.
                Рисование на QGraphicsScene при зажатой кнопке мыши Подскажите, пожалуйста! Как данный класс можно дополнить, чтобы созданные объекты можно было перемещать мышкой по сцене?
                Дмитрий
                ДмитрийFeb. 3, 2025, 4:24 p.m.
                Создание deb-пакета. Как создать ярлык на рабочем столе после установки собственного deb-пакета? Всем привет. Сделал свой deb-пакет с программой. Всё устанавливается и работает. Ставлю по пути /usr/bin/my_application. Как для пользователя при установке пакета сразу создать ярлык на раб…
                NW
                Nayo WaiJan. 30, 2025, 7:22 p.m.
                не запускается компьютер!!! Не запускается компьютер (точнее работает блок , но сам монитор вообще жесть)В общем я ничего с интернета не скачивала в последнее время. На компе никаких левых пр…
                n
                nklyJan. 3, 2025, 12:52 p.m.
                Нужно запретить перемещение только некоторых итемов, остальные перемещать можно. Вопрос решен. Узнать QModelIndex элемента на который мы перетаскиваем другой элемент, можно с помощью функции indexAt(event->position().toPoint()) представления QTreeViev вызываемой в переопр…
                M
                MarselAug. 17, 2023, 12:26 a.m.
                OAuth2.0 через VK, получение email Спасибо большое за помощь и простите за то что отнял время своей невнимательностью.

                Follow us in social networks