泛化迭代视图模型

2024-09-30 05:33:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道是否有可能使下面的函数成为泛型的,这样它就可以遍历任何给定的模型,并且不需要像下面的函数那样在该模型中声明所有字段

def CustomerTable(ExampleModel):
    CustomerInfo = ExampleModel.objects.all()
    CustomerJson = []
    for customers in CustomerInfo:
        CustomerJson.append({
                            'ID': customers.ID,
                            'Title': customers.Title,
                            'Name': customers.Name,
                            'Description': customers.Description,
                            'Location': customers.Location,
                            'DateAdded': customers.DateAdded,
                            })
    CustomerTable = {'Records' :CustomerJson}
    Return HttpResponse (CustomerTable)

谢谢你的帮助


Tags: 函数name模型id声明titlelocationdescription
2条回答

可以将模型作为参数传递给函数:

def CustomerTable(anymodel):

然后您可以在

anymodel._meta.get_all_field_names()

但是,字段的映射并不精确(外键的fieldname\u id)

所以,正如程的回答中已经提到的,最好使用

anymodel._meta.get_fields()

相关问题 更多 >

    热门问题