Say I have a Django class something like this:
class Person(models.Model): name = models.CharField(max_length=50) # ...
How can I programatically obtain the max_length
value for the name
field?
You can't create a form or use any other Django features with it. If you inherit the models. Model version, your Employee class will have all the methods of a Django Model, and it will inherit the first_name field as a database field that can be used in a form.
pk is more independent from the actual primary key field i.e. you don't need to care whether the primary key field is called id or object_id or whatever. It also provides more consistency if you have models with different primary key fields. id is also a built-in function in Python, I prefer to use pk because of that.
pk is short for primary key, which is a unique identifier for each record in a database. Every Django model has a field which serves as its primary key, and whatever other name it has, it can also be referred to as "pk".
Person._meta.get_field('name').max_length
will give you this value. But having to use _meta
suggests this is something you shouldn't do in normal usage.
Edit: as Carl pointed out, this naming is misleading and it does seem quite acceptable to use it: http://www.b-list.org/weblog/2007/nov/04/working-models/
Read more at Django Docs: https://docs.djangoproject.com/en/dev/ref/models/meta/#django.db.models.options.Options.get_field
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With