MU
Maciej Urmański11. Dezember 2019 06: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:

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)

Рекомендуємо хостинг TIMEWEB
Рекомендуємо хостинг TIMEWEB
Stabiles Hosting des sozialen Netzwerks EVILEG. Wir empfehlen VDS-Hosting für Django-Projekte.

Magst du es? In sozialen Netzwerken teilen!

7
Evgenii Legotckoi
  • 11. Dezember 2019 06:52

Hello,

Try this

from django.db.models import Count
embeds = Embed.objects.annotate(total=Count('added_by'))
embeds[0].total
    MU
    • 11. Dezember 2019 07:52
    • (bearbeitet)

    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
      • 11. Dezember 2019 08:07
      • (bearbeitet)

      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
        • 11. Dezember 2019 08:08

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

          Evgenii Legotckoi
          • 11. Dezember 2019 08:11
          • (bearbeitet)

          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
            • 11. Dezember 2019 08:14

            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
              • 11. Dezember 2019 08:27
              • Die Antwort wurde als Lösung markiert.

              Thank you! Now works, and this is solution.

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

                Kommentare

                Nur autorisierte Benutzer können Kommentare posten.
                Bitte Anmelden oder Registrieren
                Letzte Kommentare
                A
                ALO1ZE19. Oktober 2024 08:19
                Fb3-Dateileser auf Qt Creator Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html
                ИМ
                Игорь Максимов5. Oktober 2024 07:51
                Django – Lektion 064. So schreiben Sie eine Python-Markdown-Erweiterung Приветствую Евгений! У меня вопрос. Можно ли вставлять свои классы в разметку редактора markdown? Допустим имея стандартную разметку: <ul> <li></li> <li></l…
                d
                dblas55. Juli 2024 11:02
                QML - Lektion 016. SQLite-Datenbank und das Arbeiten damit in QML Qt Здравствуйте, возникает такая проблема (я новичок): ApplicationWindow неизвестный элемент. (М300) для TextField и Button аналогично. Могу предположить, что из-за более новой верси…
                k
                kmssr8. Februar 2024 18:43
                Qt Linux - Lektion 001. Autorun Qt-Anwendung unter Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
                Qt WinAPI - Lektion 007. Arbeiten mit ICMP-Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
                Jetzt im Forum diskutieren
                J
                JacobFib17. Oktober 2024 03:27
                добавить qlineseries в функции Пользователь может получить любые разъяснения по интересующим вопросам, касающимся обработки его персональных данных, обратившись к Оператору с помощью электронной почты https://topdecorpro.ru…
                JW
                Jhon Wick1. Oktober 2024 15:52
                Indian Food Restaurant In Columbus OH| Layla’s Kitchen Indian Restaurant If you're looking for a truly authentic https://www.laylaskitchenrestaurantohio.com/ , Layla’s Kitchen Indian Restaurant is your go-to destination. Located at 6152 Cleveland Ave, Colu…
                КГ
                Кирилл Гусарев27. September 2024 09:09
                Не запускается программа на Qt: точка входа в процедуру не найдена в библиотеке DLL Написал программу на C++ Qt в Qt Creator, сбилдил Release с помощью MinGW 64-bit, бинарнику напихал dll-ки с помощью windeployqt.exe. При попытке запуска моей сбилженной программы выдаёт три оши…
                F
                Fynjy22. Juli 2024 04:15
                при создании qml проекта Kits есть но недоступны для выбора Поставил Qt Creator 11.0.2. Qt 6.4.3 При создании проекта Qml не могу выбрать Kits, они все недоступны, хотя настроены и при создании обычного Qt Widget приложения их можно выбрать. В чем может …

                Folgen Sie uns in sozialen Netzwerken