2014-12-04 60 views
0

我有以下模型和表;将列添加到queryset和django-table2表

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?

此外,如果我可以生成sql查询与aditional列“年龄”我怎么能将它添加到表? 我想知道是否应该在这种情况下使用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") 

在此先感谢。

回答

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 
+0

感谢您的帮助,我昨天解决了,请参阅编辑。再次感谢 – 2014-12-05 20:35:03