如何通过Django中的自定义管理操作获取关联模型?

时间:2015-02-22 05:39:45

标签: python django jinja2

Part 2这个问题被单独提出并回答。

我有ReportReportTemplate

+----+----------+---------------+-------------+
| id |  title   |     data      | template_id |
+----+----------+---------------+-------------+
|  1 | report 1 | {data: [...]} |           1 |
+----+----------+---------------+-------------+

reports table

+----+-----------+---------------+------------+
| id |   title   |    markup     |    css     |
+----+-----------+---------------+------------+
|  1 | template1 | <doctype!>... | body {.... |
+----+-----------+---------------+------------+

templates table

报告属于ReportTemplate。 ReportTemplate有很多报告。

我在admin.py中为print_as_pdf

提供了自定义管理操作
class ReportAdmin(admin.ModelAdmin):
    fields = ['commodity', 
    'date',
    'trade_period',
    'quantity_cutoff',
    'data',
    'template',
    'title']

    actions = ['print_as_pdf']

    def print_as_pdf(self, request, queryset):
        return
    print_as_pdf.short_description = 'Generate as pdf'

这些是模特:

class ReportTemplate(models.Model):
    title = models.CharField(max_length=50)
    markup = models.TextField(default = 'markup here...')
    styles = models.TextField(default = 'styles here...')

    # __unicode__ on Python 2
    # __str__ on Python 3
    def __unicode__(self):
        return self.title

class Report(models.Model):
    title = models.CharField(max_length=50)
    commodity = models.CharField(max_length=10)
    date = models.DateTimeField('date traded')
    trade_period = models.CharField(max_length=10, default='open')
    quantity_cutoff = models.IntegerField(default=0)
    printed = models.BooleanField(default=0)
    datetime_email_sent = models.DateTimeField('date email sent', blank=True, null=True)
    data = models.TextField(default = 'data here...')
    template = models.ForeignKey(ReportTemplate)

我想做的是:

  1. 检索关联的ReportTemplate及其markup字段值
  2. 将报告的data字段值通过markup值放在1中,该值是用jinja2标记写的
  3. 使用weasyprint并从2打印出数据填充标记为pdf
  4. 我被困在第1步。

    根据参数selfrequestqueryset,如何检索关联的ReportTemplate及其markup字段值?

    更新1:

    我试过这个来测试给出的答案之一。

    import logging
    
    logger = logging.getLogger(__name__)
    
    # .... code here ...
    
    def print_as_pdf(self, request, queryset):
            for report in queryset:
                markup = report.template.markup
                logger.debug(markup)
            return
    

    更新2:

    # Logging
    LOGGING = {
        'version': 1,
        'disable_existing_loggers': False,
        'handlers': {
            'file': {
                'level': 'DEBUG',
                'class': 'logging.FileHandler',
                'filename': '/var/virtual/WebApps/virtualenvs/WeasyPrintProject/weasyprint_site/debug.log',
            },
        },
        'loggers': {
            'reports.admin': {
                'handlers': ['file'],
                'level': 'DEBUG',
                'propagate': True,
            },
        },
    }
    

    在我的settings.py

    中写了这个

    生成一个debug.log

    但是,debug.log的内容为空

    更新3:

    需要明确更改

    logger = logging.getLogger(__name__)
    

    logger = logging.getLogger('reports.admin')
    

1 个答案:

答案 0 :(得分:1)

只需获取template模型的Report字段:

def print_as_pdf(self, request, queryset):
    for report in queryset:
        markup = report.template.markup
        ...
print_as_pdf.short_description = 'Generate as pdf'

更新:要use the logger,您应该在源文件的开头添加这两行:

import logging

logger = logging.getLogger(__name__)