MU
Maciej UrmańskiНаурыз 10, 2019, 1:01 Т.Қ.

Django list of subscribed objects

django, Django, python

Hi, I try to show user object from category which they subscribe. But don't know exacly how.

I have four models:
Board ( category )
Subject
Embed and Subscribe (foreign to user and to board)

class Board(models.Model):
    title = models.CharField(max_length=255, verbose_name='Tytuł')
    slug = AutoSlugField(populate_from='title', unique=True)
    image = models.ImageField(upload_to='board-cover', verbose_name='Tło kategorii', null=True, blank=True)
    body = models.TextField(verbose_name='Opis kategorii')
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True)

class Subscribe(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='subscribed_users')
    board = models.ForeignKey(Board, on_delete=models.CASCADE, related_name='subscribed_boards')
    created_at = models.DateTimeField(auto_now_add=True)
    subscribe = models.BooleanField(default=False)

class Subject(models.Model):
    title = models.CharField(max_length=255, verbose_name='Tytuł')
    slug = AutoSlugField(populate_from='title', unique=True)
    body = models.TextField(blank=True, verbose_name='Treść')
    image = models.ImageField(upload_to='subject', null=True, blank=True)
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    active = models.BooleanField(default=True)
    created_at = models.DateTimeField(auto_now_add=True)
    board = models.ForeignKey(Board, on_delete=models.CASCADE, related_name='subjects', verbose_name='Kategoria')
    votes = GenericRelation(LikeDislike, related_query_name='subjectsvotes')

class Embed(models.Model):
    url = models.URLField(max_length=255)
    title = models.CharField(max_length=255)
    description = models.TextField()
    thumbnail_url = models.URLField(max_length=255)
    html = models.TextField()
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True)
    board = models.ForeignKey(Board, on_delete=models.CASCADE, blank=True, null=True, related_name='embeds')
    votes = GenericRelation(LikeDislike, related_query_name='embedvotes')

In my views I try something like this:

def feed(request):
    embeds = Embed.objects.filter(author=request.user)
    subscribed_ids = request.user.subscribed_users.values_list('id', flat=True)

    actions = embeds.filter(author_id__in=subscribed_ids)
    actions = actions[:10]

    return render(request, 'boards/feed.html',
                {'actions': actions})

but nothing show up.

Рекомендуем хостинг TIMEWEB
Рекомендуем хостинг TIMEWEB
Стабильный хостинг, на котором располагается социальная сеть EVILEG. Для проектов на Django рекомендуем VDS хостинг.

Ол саған ұнайды ма? Әлеуметтік желілерде бөлісіңіз!

5
Evgenii Legotckoi
  • Наурыз 11, 2019, 4:43 Т.Ж.

Hi,

it looks rightly.

Can you show print out of def feed. For example

def feed(request):
    embeds = Embed.objects.filter(author=request.user)
    print(embeds)
    subscribed_ids = request.user.subscribed_users.values_list('id', flat=True)
    print(subscribed_ids)

    actions = embeds.filter(author_id__in=subscribed_ids)
    print(actions)
    actions = actions[:10]

    return render(request, 'boards/feed.html',
                {'actions': actions})

May be you can write, I'm not sure

def feed(request):
    embeds = Embed.objects.filter(author=request.user)
    print(embeds)
    subscribed_ids = request.user.subscribed_users.values_list('id', flat=True)
    print(subscribed_ids)

    actions = embeds.filter(author__in=list(subscribed_ids))
    print(actions)
    actions = actions[:10]

    return render(request, 'boards/feed.html',
                {'actions': actions})
    MU
    • Наурыз 11, 2019, 5:46 Т.Ж.
    • (өңделген)

    Hmm:

    <QuerySet [<Embed: Embed object (11)>, <Embed: Embed object (10)>, <Embed: Embed object (9)>, <Embed: Embed object (8)>, <Embed: Embed object (1)>]>
    <QuerySet [2, 3, 5]>
    <QuerySet []>
    

    I print this and actions is empty. I try also with list and still the same.

      Evgenii Legotckoi
      • Наурыз 11, 2019, 5:54 Т.Ж.

      may be, you want filter board instead of embed?

      actions = Board.objects.filter(author__in=list(subscribed_ids))
      
        MU
        • Наурыз 11, 2019, 6:06 Т.Ж.
        • (өңделген)

        Now I get Board instead of embed. :D

        Hmm in evileg You have too subscribe option to category articles I see. How You do this? :)

        Before I try to add manytomanyfield to board instead of create new model Subscribe but i don't know how to query that way. Now I see in subscribe model too don't know how. :D

          Evgenii Legotckoi
          • Наурыз 11, 2019, 6:17 Т.Ж.
          • (өңделген)

          I have created subscriptions similar like LikeDislike model, because of I need generic Subscription for all types of content (It may be category of articles, forum, bookmarks, forum topics and so on).

            Пікірлер

            Тек рұқсаты бар пайдаланушылар ғана пікір қалдыра алады.
            Кіріңіз немесе Тіркеліңіз
            OI
            • Ora Iro
            • Жел. 24, 2024, 6:38 Т.Ж.

            C++ - Тест 001. Первая программа и типы данных

            • Нәтиже:40ұпай,
            • Бағалау ұпайлары-8
            AD

            C++ - Тест 004. Указатели, Массивы и Циклы

            • Нәтиже:50ұпай,
            • Бағалау ұпайлары-4
            m
            • molni99
            • Қаз. 26, 2024, 1:37 Т.Ж.

            C++ - Тест 004. Указатели, Массивы и Циклы

            • Нәтиже:80ұпай,
            • Бағалау ұпайлары4
            Соңғы пікірлер
            ИМ
            Игорь МаксимовҚар. 22, 2024, 11:51 Т.Ж.
            Django - Оқулық 017. Теңшелген Django кіру беті Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
            Evgenii Legotckoi
            Evgenii LegotckoiҚаз. 31, 2024, 2:37 Т.Қ.
            Django - Сабақ 064. Python Markdown кеңейтімін қалай жазуға болады Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
            A
            ALO1ZEҚаз. 19, 2024, 8:19 Т.Ж.
            Qt Creator көмегімен fb3 файл оқу құралы Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html
            ИМ
            Игорь МаксимовҚаз. 5, 2024, 7:51 Т.Ж.
            Django - Сабақ 064. Python Markdown кеңейтімін қалай жазуға болады Приветствую Евгений! У меня вопрос. Можно ли вставлять свои классы в разметку редактора markdown? Допустим имея стандартную разметку: <ul> <li></li> <li></l…
            d
            dblas5Шілде 5, 2024, 11:02 Т.Ж.
            QML - Сабақ 016. SQLite деректер қоры және онымен QML Qt-та жұмыс істеу Здравствуйте, возникает такая проблема (я новичок): ApplicationWindow неизвестный элемент. (М300) для TextField и Button аналогично. Могу предположить, что из-за более новой верси…
            Енді форумда талқылаңыз
            n
            nklyҚаң. 3, 2025, 2:52 Т.Ж.
            Нужно запретить перемещение только некоторых итемов, остальные перемещать можно. Вопрос решен. Узнать QModelIndex элемента на который мы перетаскиваем другой элемент, можно с помощью функции indexAt(event->position().toPoint()) представления QTreeViev вызываемой в переопр…
            AW
            Ayden WatkinsҚаң. 2, 2025, 12:09 Т.Ж.
            Why Paying for a Research Paper Can Be a Smart Choice Writing a research paper can be a daunting task, especially when faced with tight deadlines, complex topics, or a lack of resources. For many students, paying for a research paper is a practical…
            p
            pimacontrols85Жел. 31, 2024, 9:39 Т.Ж.
            Finding the Right Rittal Small Enclosure for Your Needs Rittal is a leading manufacturer of enclosures for industrial and IT applications. Their small enclosures offer a compact and reliable solution for a wide range of needs, from housing electronic…
            Donald Randolph
            Donald RandolphЖел. 30, 2024, 2:59 Т.Ж.
            Personal Injury lawyer Santa Monica As an experienced Santa Monica personal injury lawyer, Donald C. Randolph has recovered over $100 Million in verdicts and settlements for our clients. In severe injury cases, this compensation i…
            Nirvana Yoga School
            Nirvana Yoga SchoolЖел. 30, 2024, 5:13 Т.Ж.
            OAuth2.0 через VK, получение email Nirvana Yoga School is one of the most trusted and reputed traditional Rishikesh yoga courses , India certified by Yoga Alliance, USA. We aim to spread traditional yoga teachings so t…

            Бізді әлеуметтік желілерде бақылаңыз