MU
Maciej Urmański11. Dezember 2019 06:27
Count user objects e.g posts
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
Stabiles Hosting des sozialen Netzwerks EVILEG. Wir empfehlen VDS-Hosting für Django-Projekte.Magst du es? In sozialen Netzwerken teilen!
Kommentare
sf
- sdfsdfkp fgskpgokspdog
- 14. Oktober 2024 15:09
C++ - Тест 004. Указатели, Массивы и Циклы
- Ergebnis:90punkte,
- Bewertungspunkte8
МВ
- Максим Васильев
- 2. Oktober 2024 04:14
Qt - Тест 001. Сигналы и слоты
- Ergebnis:68punkte,
- Bewertungspunkte-1
ЛС
- Лев Семенов
- 30. September 2024 11:04
C++ - Тест 001. Первая программа и типы данных
- Ergebnis:53punkte,
- Bewertungspunkte-4
Letzte Kommentare
Fb3-Dateileser auf Qt Creator Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html
ИМ
Django – Lektion 064. So schreiben Sie eine Python-Markdown-Erweiterung Приветствую Евгений! У меня вопрос. Можно ли вставлять свои классы в разметку редактора markdown? Допустим имея стандартную разметку: <ul> <li></li> <li></l…
Игорь Максимов5. Oktober 2024 07:51
QML - Lektion 016. SQLite-Datenbank und das Arbeiten damit in QML Qt Здравствуйте, возникает такая проблема (я новичок): ApplicationWindow неизвестный элемент. (М300) для TextField и Button аналогично. Могу предположить, что из-за более новой верси…
Qt Linux - Lektion 001. Autorun Qt-Anwendung unter Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
АК
Qt WinAPI - Lektion 007. Arbeiten mit ICMP-Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
Анатолий Кононенко5. Februar 2024 01:50
Jetzt im Forum diskutieren
добавить qlineseries в функции Пользователь может получить любые разъяснения по интересующим вопросам, касающимся обработки его персональных данных, обратившись к Оператору с помощью электронной почты https://topdecorpro.ru…
ИМ
Реализация навигации по разделам Спасибо Евгений!
Игорь Максимов3. Oktober 2024 04:05
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…
КГ
Не запускается программа на Qt: точка входа в процедуру не найдена в библиотеке DLL Написал программу на C++ Qt в Qt Creator, сбилдил Release с помощью MinGW 64-bit, бинарнику напихал dll-ки с помощью windeployqt.exe. При попытке запуска моей сбилженной программы выдаёт три оши…
Кирилл Гусарев27. September 2024 09:09
при создании qml проекта Kits есть но недоступны для выбора Поставил Qt Creator 11.0.2. Qt 6.4.3 При создании проекта Qml не могу выбрать Kits, они все недоступны, хотя настроены и при создании обычного Qt Widget приложения их можно выбрать. В чем может …
Hello,
Try this
Hmm this count every recipes. Not only one user.
I try something like that from stackoverflow:
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
May be, because, you don`t have field "author" in your model... ?
And in this code you get object of model
Therefore you cannot use objects in this row
Because of objects can be used only in this situation
And I don`t see author instance in your code.
You can write something else like this
But you should get author instance from anywhere, for example request.user
Yeah I edit my answer and change to added_by. But still this don't work.
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
or this
Thank you! Now works, and this is solution.