简体   繁体   中英

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.

You can do something like this...

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM