Florent
Florent

Reputation: 1928

Multiple fields assignment in Django models

I have several fields in my models that share the same caracteristics and I would like to declare them in one line with something like this:

class Shop(models.Model):
    id, name, brand = models.CharField(max_length=12)

Or:

class Shop(models.Model):
    id = name = brand = models.CharField(max_length=12)

instead of doing this:

class Shop(models.Model):
    id = models.CharField(max_length=12)
    name = models.CharField(max_length=12)
    brand = models.CharField(max_length=12)

But Django complains with a TypeError in the first case saying that 'CharField' object is not iterable, and with admin.E108 error in the second case.

So my question is how can I declare multiple fields that share the same caracteristics in a single line of code with Django? it looks to me that the second cases is not related to Python.

Upvotes: 0

Views: 175

Answers (1)

Swetank Poddar
Swetank Poddar

Reputation: 1291

You can do something like this...

id, name, brand = [models.CharField(max_length=12) for i in range(3)]

Upvotes: 2

Related Questions