MU
Dec. 11, 2019, 5: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.
7

Hello,

Try this

from django.db.models import Count
embeds = Embed.objects.annotate(total=Count('added_by'))
embeds[0].total
MU

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

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

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

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}

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

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
How to become an author?

Contribute to the evolution of the EVILEG community.

Learn how to become a site author.

Learn it
Donate

Good day, Dear Users!!!

I am Evgenii Legotckoi, developer of EVILEG. And it is my hobby project, which helps to learn programming another programmers and developers

If the site helped you, and you want also support the development of the site, than you can donate by following ways

PayPalYandex.Money
Timeweb

Let me recommend you the excellent hosting on which EVILEG is located.

For many years, Timeweb has been proving his stability.

For projects on Django I recommend VDS hosting

View Hosting Timeweb
June 5, 2020, 11:20 p.m.
Aleksej

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

  • Result:60points,
  • Rating points-1
June 5, 2020, 11:15 p.m.
Aleksej

C++ - Test 001. The first program and data types

  • Result:53points,
  • Rating points-4
V
June 5, 2020, 4:47 p.m.
Vladzo

C++ - Test 005. Structures and Classes

  • Result:83points,
  • Rating points4
Last comments
June 5, 2020, 10:52 a.m.
progammist

Распознавание изображений на Python с помощью TensorFlow и Keras

Огромное спасибо за метериал, по-больше бы подобных статей (с подробным описанием работы и примерами применения) на тему современных технологий. Вопрос поразмышлять. На текущий момент реал…
June 5, 2020, 1:39 a.m.
Evgenij Legotskoj

Qt/C++ - Tutorial 091. How to write a custom delegate controlling the highlighting of a row in a table

По-моему, смысла в этом нет особого. Если делегат будет игнорировать настройки таблицы, то это приведёт ещё к большему непониманию, что вообще происходит, для программиста, который после вас буд…
June 5, 2020, 1:34 a.m.
IscanderChe

Qt/C++ - Tutorial 091. How to write a custom delegate controlling the highlighting of a row in a table

Сижу, размышляю: можно ли переписать делегата так, чтобы независимо от настроек строк выделялись строки?
June 5, 2020, 1:31 a.m.
Evgenij Legotskoj

Qt/C++ - Tutorial 091. How to write a custom delegate controlling the highlighting of a row in a table

Понятно. Я не обратил внимания на то, что там было в старом коде по настройкам строк :)
Now discuss on the forum
s
June 6, 2020, 1:54 a.m.
shuric

Qt/C++ Определение положения курсора над действие(кнопкой) в QToolBar

Доброго дня. Возник вопрос - как можно определить что курсор находится над определенным действием(кнопкой) в qtoolbar ? mainwindow.cpp MainWindow::MainWi…
s
June 6, 2020, 12:45 a.m.
shuric

Qt/C++ особенности QProxyStyle

Да, Вы правы. Код был скопирован с сайта (уже не помню с какого), но решил пойти по пути более легком. Пришлось переписать - кому интересно: использовал stackedWidget для пе…
June 5, 2020, 11:08 p.m.
Aleksej

Посоветуйте новичку (базы данных и Qt, что учить)

Блин, а я недавно купил Шлее Qt 5.10 :( С детства хотел стать программистом, баловался Паскалем, писал простенькие программки на Delphi, создавал движок на php, изучал C (забросил и перешел на п…
June 5, 2020, 1:09 p.m.
IscanderChe

QPlainTextEdit настройка цвета фона

Вечер добрый. Пытаюсь настроить цвет фона QPlainTextEdit следующим образом: CodeEditor::CodeEditor(QWidget *parent) : QPlainTextEdit(parent){ ... QPalette::ColorRole role = bac…
June 5, 2020, 6:13 a.m.
IscanderChe

Фильтр для QtableView sql

Добрый день. Для такой фильтрации необходимо использовать QSortFilterProxyModel. В оффдоках есть хороший пример.
About
Services
© EVILEG 2015-2020
Recommend hosting TIMEWEB