【问题标题】:Django - Filtering Related Sets in TemplatesDjango - 过滤模板中的相关集
【发布时间】:2020-04-01 14:15:42
【问题描述】:

我有两个模型;

class Customer(models.Model):
    first_name = models.CharField(max_length=20)
    last_name = models.CharField(max_length=20)
    email = models.EmailField()

class WorkOrder(models.Model):
    date_created = models.DateField('Date', default=datetime.now)
    due_date = models.DateField('Due Date')
    customer = models.ForeignKey(Customer, on_delete=models.CASCADE, verbose_name='Customer')
    STATUS_CHOICES = [
        ('pending', 'Pending'),
        ('approved', 'Approved'),
        ('completed', 'Completed'),
        ('cancelled', 'Cancelled'),
    ]
    status = models.CharField('Status of the work order', max_length=10, choices=STATUS_CHOICES, default='pending')
    description = models.TextField('Description of the work')

我编写了一个基于类的列表视图来制作客户列表:


class ReportCustomerListView(ListView):

    model = CustomUser
    template_name = 'reports/customer_report.html'

    def get_queryset(self):

        return CustomUser.objects.filter(is_staff=False).filter(is_superuser=False)

我想为用户准备一份关于其客户的报告,因此我想显示客户有多少待处理、已批准和已完成的工作订单。我的列表模板是;

<table class="table table-striped">
        <thead>
            <tr>
                <th scope="col">#</th>
                <th scope="col">First Name</th>
                <th scope="col">Last Name</th>
                <th scope="col">Company</th>
                <th scope="col">Pending Work Orders</th>
                <th scope="col">Active Work Orders</th>
                <th scope="col">Completed Work Orders</th>
                <th scope="col">Draft Bills</th>
            </tr>
        </thead>
            <tbody>
                {% for customer in object_list %}
                <tr>
                    <th scope="row">{{ forloop.counter }}</th>
                    <td>{{ customer.first_name }}</td>
                    <td>{{ customer.last_name }}</td>
                    <td>{{ customer.company.company_name }}</td>
                    ...
                    ...
                    ... // the part where I am stuck

但是在阅读了 4 个小时之后我就迷失了,我更加困惑。我知道我可以从

访问工单
>>> Users.objects.get(pk=pk).workorder_set

我的问题是如何让客户工单计数模板上的每个状态类型?换句话说,如何过滤模板上对象列表中的相关字段?

过滤视图等其他方法也适用于我,但我不知道该怎么做。

非常感谢您的宝贵时间......

【问题讨论】:

    标签: python django python-3.x django-templates


    【解决方案1】:

    如果您想获取相关对象,那么您应该尝试在您的应用程序中安装此django-taggit 并尝试此代码... 视图.py

    def tagged(request, slug):
    tag = get_object_or_404(Tag, slug=slug)
    # Filter posts by tag name  
    posts = Post.objects.filter(tags=tag)
    context = {
        'tag':tag,
        'posts':posts,
    }
    

    【讨论】:

    • 还有其他不依赖第三方应用的方式吗?
    猜你喜欢
    • 2018-09-02
    • 2023-04-11
    • 1970-01-01
    • 2020-10-30
    • 2017-06-22
    • 2011-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多