Reputation: 2703
Hi is there a way to filter on field attributes instead of field values in Django?
For example, for my GUI layout i want to know the ordering of fields ordered by max_length. My model:
class Person(models.Model):
name1 = models.CharField(max_length=220, default="")
name2 = models.CharField(max_length=90, default="")
name3 = models.CharField(max_length=30, default="")
name4 = models.CharField(max_length=130, default="")
name5 = models.CharField(max_length=10, default="")
I want to be able to find the length of the longest CharField in my model, in this case 220. How can i do that?
This is just an simplified example, but is similar to the functionality i need. To give insight in the real-world situation i am facing: I added a custom attribute to my model "gui_serial_number", I have partially static models with fields like:
a = CharField(gui_serial_number=10...)
b = CharField(gui_serial_number=20...)
....
n = CharField(gui_serial_number=50...)
I made an dynamic interface in which Fields can be dynamically added to the model (with type() and add_to_class() etc), and the user can give the place in the GUI where the field should be placed. I want to be able to automagically define the gui_serial_number to be "max+10" when no gui_serial_number is given.
Upvotes: 1
Views: 322
Reputation: 1625
Maybe it's not beautiful, but to find the length of the longest CharField of Person
you can do this:
from operator import attrgetter
sorted([field for field in Person._meta.fields if isinstance(field, models.CharField)],
key=attrgetter('max_length'))[-1].max_length
Upvotes: 1