Django:在视图中创建自定义对象列表,并将其传递给模板以进行循环 [英] Django : Create custom object list in the view and pass it to template to loop over

查看:120
本文介绍了Django:在视图中创建自定义对象列表,并将其传递给模板以进行循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在视图中创建一个自定义对象列表,并将其传递给模板。在模板中,我想遍历列表并显示信息。

I want to create a custom object list in the view and pass it to the template. In the template I want to loop over the list and display the information.

我的模型是

class CustomUser(AbstractUser):
    def __str__(self):
        return self.email

class Post(models.Model):
    author = models.ForeignKey(CustomUser,on_delete=models.CASCADE,)
    text = models.TextField()
    created_date = models.DateTimeField(default=timezone.now)
    published_date = models.DateTimeField(blank=True, null=True)
    post_url = models.URLField(max_length = 200, blank = True)
    slug = models.SlugField(unique=True, blank=True)

class subscription(models.Model):
    creator = models.ForeignKey(CustomUser,default=None, null=True,on_delete=models.CASCADE,related_name='creator',)
    booster = models.ForeignKey(CustomUser,default=None, null=True,on_delete=models.CASCADE,related_name='booster')
    sub_value = models.FloatField(blank = True)
    sub_id = models.TextField(blank = True)
    status = models.BooleanField(default=False)
    dateSubscribed = models.DateTimeField(default=timezone.now)
    dateSubscriptionEnded = models.DateTimeField(default=timezone.now)
    paymentCount = models.FloatField(default= 0)

我要过滤对象来自下面的订阅模型

I want to filter objects from subscription model like below

subs = subscription.objects.filter(booster = request.user)

然后在上述子对象列表中找到创建者,并为每个创建者获取名称,帖子数和订阅者数。将此添加到自定义列表,然后将其传递到模板以遍历并显示模板中的信息。有人可以帮助我如何创建此自定义列表。谢谢!

Then find creators in the above subs object list and for each creator get the name, numbers Posts, and number of Subscribers. Add this to custom list and pass it to the template to loop over and display the information in the template. Can someone help me how to create this custom list. Thanks!

推荐答案

好的,这是减去订阅者的基础知识,因为我看不到这种关系。这是解析帖子名称和数量的方法。 \

Ok so here are the basics minus the subscribers because I don't see the relation clearly. This is how to parse the name and the number of posts. \

my_list = []

for sub in subs:
    name = sub.creator.name
    auth_id = sub.creator.id
    posts = Post.objects.filter(author=auth_id)
    num_of_posts = len(posts)
    my_list.append({
        'name':name,
        'post_count': num_of_posts,
    })

然后您将通过模板上下文传递mylist。

then you would pass mylist thru the template context.

这篇关于Django:在视图中创建自定义对象列表,并将其传递给模板以进行循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆