1

I have a Model with 100 identical fields named field_1, field_2, and so on. Is there a method to define these fields in a cycle (just to avoid writing and maintaining 100 rows)?

That is, now I have to name each field separately:

class MyModel(models.Model):
    field_1 = models.CharField(...)
    field_2 = models.CharField(...)
    field_3 = models.CharField(...)
    field_4 = models.CharField(...)
    field_5 = models.CharField(...)
    ...

I would like something like:

class MyModel(models.Model):
    for i in range(1, 101):
        eval("field_%d = models.CharField(...)"%i)

but, of course, I do not like eval.

Any hint?

NOTE I need such a model because I'm doing a two-step importation from CSV/Excel: first, I put Excel rows into this table, then process the table and import data in the actual application (where I'm using ForeignKeys, as suggested)

Don
  • 16,928
  • 12
  • 63
  • 101
  • 6
    Databases... you're doing it wrong. – Daniel Roseman May 17 '11 at 10:28
  • Maybe I'm facing the wrong problem. Can you suggest an alternative solution? – Don May 17 '11 at 10:31
  • 2
    Maybe what you need is a separate table/model to store the field values, and just use a ForeignKey to link to them. – john2x May 17 '11 at 10:38
  • You can take a look at this link: [How to dynamically add fields to a Django model](http://mixedcase.nl/articles/2009/11/26/how-dynamically-add-fields-django-model/) – solartic May 17 '11 at 13:06

1 Answers1

0

Honestly, I have not looked at this or used it, but check out this snippet. It is all about CSV import.

what does your data look like? If it's like most excel sheets, the fields are in columns and the data is in rows. In that case maybe you dont need 100 fields in your model, make a field for each columns

+-----+---------+----------+-------+
| id  |  name   |  address | phone |
+-----+---------+----------+-------+
| 1   | person1 |   blah   |  foo  |
| ... |   ...   |   ...    |  ...  |
| 100 |person100|   bar    |  baz  |

for example this data only need 3 fields (or 4 if the ID is explicitly defined), you wouldn't need to (and shouldn't) define 100 fields for each row. Now, if you have 100 columns of data, ok there may be a reason to want to automate, but have generic named fields seems... less than useful. So if the data is always the same format (in terms of columns), it may be worth putting the leg work into descriptive model fields.

j_syk
  • 6,511
  • 2
  • 39
  • 56
  • The Excel file has a set of custom columns and I have to manage them without knowing it when defining the model (e.g. if the Excel file has the columns 'favourite color' and 'singing level' I have to add these two attributes to my Person model) and I only forced the maximum number of these columns (100) – Don May 17 '11 at 14:16