开发者

Django: dynamically defining model fields

I have a Mod开发者_如何学编程el 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)


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜