【问题标题】:Add columns to queryset and django-table2 table向 queryset 和 django-table2 表添加列
【发布时间】:2014-12-04 17:38:40
【问题描述】:

我有以下模型和表格;

class Person(models.Model):
    first_name = models.CharField(max_length=200)
    last_name = models.CharField(max_length=200)
    user = models.ForeignKey("auth.User")
    dob = models.DateField()

# tables.py
class PersonTable(tables.Table):
    class Meta:
        model = Person

我想生成一个 SQL 查询来计算我的 MySQL 数据库中每个人的更新年龄,每次检索对象时都使用“dob”,django 可以吗?

此外,如果我可以生成带有附加列“age”的 sql 查询,我该如何将它添加到表中? 我想知道在这种情况下我是否应该使用 django-table2。

编辑:我已经解决了这样做的问题。

我在 MYSQL 上创建了一个函数,用于根据 arg 类型的日期计算年龄。 然后我在我的视图中在原始 sql 查询中使用了这个函数。

def get_persons(request):
    list_people = Person.objects.raw("SELECT *, age(date_birth) AS edad FROM mytable)

为了将这个新的年龄列添加到我的表中,我创建了一个新的表类并添加了两列“年龄”和“详细信息”,如下所示:

class TablaBeneficiarios(tables.Table):
    age= tables.Column(orderable=True,verbose_name= "Age")
    detail= tables.TemplateColumn('<a href="/reports/beneficiario/{{record.id_beneficiario}}">Ver</a>',verbose_name="Acciones") #just a link column

    class Meta:
        model = FormularioA
        attrs = {"class": "paleblue"}
        fields = ("cod_pais", "num_familia", "num_miem_familia","fecha_ingreso_ret", "nombre", "prim_apellido",
                  "seg_apellido", "sexo", "etnia", "responsable", "age","detail")

提前致谢。

【问题讨论】:

    标签: python mysql sql django django-tables2


    【解决方案1】:
    class Person(models.Model):
        # ...
    
        @property age(self):
            result_age = 'some queryset that return one column and one row' or datetime.date.today() - self.dob
            return result_age
    
    
    class PersonTable(tables.Table):
        age = tables.Column('Custom name', order_by=('dob', ))  #  you cannot order by property, so put dob or orderable=False 
    
        class Meta:
            model = Person
    

    【讨论】:

    • 感谢您的帮助,我昨天解决了,请参阅编辑。再次感谢
    猜你喜欢
    • 2014-10-08
    • 2019-06-22
    • 1970-01-01
    • 2015-10-12
    • 2012-02-04
    • 2021-07-16
    • 2017-10-08
    • 2020-10-01
    • 2020-12-12
    相关资源
    最近更新 更多