0

I was wondering if its possible to make the below function generic so that it iterates through any given model and does not require all the fields to be stated in that model like the below function does.

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)

Thanks for all the help!

BAW331
  • 53
  • 1
  • 1
  • 9

2 Answers2

1

check out this post: Django: Get list of model fields?

There are more methods you can call, so take a look at the official documentation: https://docs.djangoproject.com/en/1.8/ref/models/meta/#retrieving-all-field-instances-of-a-model

Community
  • 1
  • 1
Cheng
  • 16,824
  • 23
  • 74
  • 104
0

You can pass the model as a parameter to the function:

def CustomerTable(anymodel):

and then you can build the json iterating on the fields provided by

anymodel._meta.get_all_field_names()

however, the mapping of the fields would not be exact (fieldname_id for foreign keys).

So, as already mentioned in Cheng's answer, it's better to use

anymodel._meta.get_fields()
Pynchia
  • 10,996
  • 5
  • 34
  • 43