MU
March 10, 2019, 5:01 p.m.

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.

Virtual hosting with 10 percent discount
Virtual hosting with 10 percent discount
EVILEG offers reliable hosting with a 10% discount for virtual hosting and 5% for VPS
5

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})
0
MU

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.

0

may be, you want filter board instead of embed?

actions = Board.objects.filter(author__in=list(subscribed_ids))
0
MU

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

0

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).

0

Comments

Only authorized users can post comments.
Please, Log in or Sign up
m
May 19, 2019, 1:49 a.m.
mahhaki

Qt - Test 001. Signals and slots

  • Result:78points,
  • Rating points2
S
May 17, 2019, 1:14 p.m.
SunBro

Qt - Test 001. Signals and slots

  • Result:42points,
  • Rating points-8
b
May 17, 2019, 4:18 a.m.
banana

C++ - Тест 003. Условия и циклы

  • Result:57points,
  • Rating points-2
Last comments
May 21, 2019, 8:10 p.m.
Дмитрий

Приветствую! Я думаю дойдёт и до этого, но пока изучать его у меня нет желания.
May 20, 2019, 7:20 p.m.
Евгений Легоцкой

Добрый день! Вы не думали разместить репозиторий проекта на GitHub?
P.
May 18, 2019, 2:03 p.m.
PELMYACH .

Спасибо большое! Вскоре буду разбираться!
May 18, 2019, 9:13 a.m.
Евгений Легоцкой

Добрый день! Отнимать значение общего счётчика можно в деструкторе класса кнопки QDynamicButton::~QDynamicButton(){ ResID--;} При этом я бы ещё переустанавливал значения вс...
P.
May 14, 2019, 10:33 p.m.
PELMYACH .

Здравствуйте!А не подскажите, как можно при удалении какой либо кнопки, у щётчика отнять значение?Дабы например четвёртой кнопке соответствовал ID 4, а не 5 скажем
Now discuss on the forum
ДТ
May 22, 2019, 1:40 p.m.
Даниил Тетерин

Есть задание - сделать программу-расписание, где главное окно - календарь, в котором можно нажать на любой день, тогда откроется окно, в котором будут видны уже существующие на этот день зад...
В
May 22, 2019, 10:05 a.m.
Владислав

Данный код компилируется только для 32 битной системы, а на 64 битной выдаёт ошибку линковки LNK2019. Возможно ли как-то, используя функцию RegisterHotKey, использовать глобальные горячие клав...
I
May 22, 2019, 5:08 a.m.
Intruder

Евгений, доброго времени суток и спасибо! Все получилось.
May 20, 2019, 8:43 a.m.
Михаиллл

Кинул библиотеки в папку с проектом и в папку к компилируемым файлам.В файле проекта прописал так, но все равно выдает ту же ошибку QT += core gui networkgreaterThan(QT_MAJOR_VERSI...
May 20, 2019, 1:47 a.m.
linq

Что вы понимаете под статической сборкой приложений? В какой среде?

For registered users on the site there is a minimum amount of advertising

EVILEG
About
Services
Join us
© EVILEG 2015-2019
Recommend hosting TIMEWEB