如何使用订阅对象列表检索Django多对多字段

时间:2019-03-15 10:21:04

标签: django django-models django-views

我项目中的用户可以订阅模型板,我尝试显示用户已订阅的所有已订阅板中的所有对象。

但是不知道如何。我通过互联网搜索,但没有任何帮助。

模型板:

class Board(models.Model):
    title = models.CharField(max_length=255, verbose_name='Tytuł')
    slug = AutoSlugField(populate_from='title', unique=True)
    image = ImageField(blank=True, manual_crop="" ,verbose_name='Tło')
    body = models.TextField(verbose_name='Opis kategorii')
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    subscribers = models.ManyToManyField(User, related_name='subscribed_boards', blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

与之相关的模型(我尝试从订阅的板子显示此对象):

class Subject(models.Model):
    title = models.CharField(max_length=255, verbose_name='Tytuł')
    slug = AutoSlugField(populate_from='title', unique=True)
    body = HTMLField(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, verbose_name='Tytuł')
    description = HTMLField(verbose_name='Opis')
    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', verbose_name='Kategoria')
    votes = GenericRelation(LikeDislike, related_query_name='embedvotes')
    slug = AutoSlugField(populate_from='title', unique=True)

在视野中,我尝试这样做:

def feed(request):
    user = get_object_or_404(User, username=request.user)
    feed = user.subscribed_boards.all()
    embeds = feed.filter(embed__in=feed)
    return render(request, 'boards/feed.html',
                {'feed': feed,
                'embeds': embeds})

2 个答案:

答案 0 :(得分:2)

您当前的代码中有一个从feedfeed的循环引用。实际需要的代码要简单得多:

boards = user.subscribed_boards.prefetch_related('embeds')

您现在可以在木板上循环并在木板中嵌入:

for board in boards:
    print(board.title)
    for embed in board.embeds.all():
        print(embed.title)

上面是Python代码,展示了如何访问对象;您更可能希望在模板中进行循环。

答案 1 :(得分:0)

您可以尝试以下代码:

def feed(request):
    user = get_object_or_404(User, username=request.user)
    feed = user.subscribed_boards.all()
    embeds = user.subscribed_boards.filter(embed__in=feed)
    return render(request, 'boards/feed.html',
                {'feed': feed,
                'embeds': embeds})

请检查是否有效。