2014-12-04 71 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