Maybe easy question but I don't know how to summarize it that I would find my answer.
Is it possible to print out all available fields of model?
For example in iPython I can import model and just write model name and tab will show all available fields the models have.
Is it possible to do this in code without using some sort of shell?
I would like to use some sort of command (e.a. print_fields(self)) and get what's inside the model.
To check fields on a model I usually use ?:
>>> Person?
Type: ModelBase
Base Class: <class 'django.db.models.base.ModelBase'>
String Form: <class 'foo.bar.models.Person'>
Namespace: Interactive
File: /home/zk/ve/django/foo/bar/models.py
Docstring:
Person(id, first_name, last_name)
You can also use help(). If you have an instance of the model you can look at __dict__:
>>> [x for x in Person().__dict__.keys() if not x.startswith('_')]
<<< ['first_name', 'last_name', 'id']
If you have the model instance(s) you can simply call:
model_queryset.all().values()
https://docs.djangoproject.com/en/dev/ref/models/querysets/#django.db.models.query.QuerySet.values
For just the list of fields using the model class itself see Django: Get list of model fields?
or directly the documentation - for Django 1.10 there is a dedicated section on how to work with fields: https://docs.djangoproject.com/en/1.10/ref/models/meta/#retrieving-all-field-instances-of-a-model
I think you just want to use __dict__ on an instance of a model. (It won't give methods like tab completion in ipython though). Also using __doc__ is quite helpful usually.
Also look into inspect http://docs.python.org/library/inspect.html
Maybe try something suggested here:
data = serializers.serialize("json", models.MyModel.objects.all(), indent=4)
JSON format is easy to print and read ;)
Inspired by #zeekay's answer, use the following to see the fields and corresponding values for an instance of a model:
[x for x in Cheese.objects.all()[0].__dict__.items() if not x[0].startswith('_')]
Why don't you implement __unicode__ :
def __unicode__(self):
return self.whatever_field + self.another_field
Related
I have a next model
class MyClass(models.Model):
# fields
When I try to get __class__ it returns 'ModelBase'.
What I actually need is to find a method of how to get a class name for models.MyClass.
Is it possible without having an instance of it?
Updated:
Sorry guys, I put it wrong, what I wanted to ask was a bit different. I am probably to tired.
This questions actually duplicates:
Get class name of django model
MyClass.__name__ should return the name of the class as a string.
.__name__ in general is the best way to get variables and functions names.
Try MyClass.__name__.
Django models are derived from the ModelBase, which is the Metaclass for all models.
I got two models, for example:
Parent(models.Model):
mytext= models.Chafield(max_lenght=250, blank=True)
Child(Parent):
mytext_comment=models.Chafield(max_lenght=250)
But in child I want mytext to be obligatory.
Do it will be sufficient to invoke mytext.blank=False in child __init__ ?
Caution this are not abstract methods because I want to be able to use Manager on Parent (Parent.objects.all() for example)
I don't think its possible. From Django Documentation:
This restriction only applies to attributes which are Field instances.
Normal Python attributes can be overridden if you wish. It also only
applies to the name of the attribute as Python sees it: if you are
manually specifying the database column name, you can have the same
column name appearing in both a child and an ancestor model for
multi-table inheritance (they are columns in two different database
tables).
PS: I tried to like you suggested, but I get error like unicode object has no attribute blank
Hmm you can try this solution:
Parent(models.Model):
mytext= models.Chafield(max_lenght=250, blank=True)
Child(Parent):
mytext_comment=models.Chafield(max_lenght=250)
Child._meta.get_field('mytext').blank = True
Can you please let me know if it works ?
As the discussion goes on I think the correct answer is:
You don't do it on model level. I should do this kind of validation on form level not in a model. Best places are: form fields parameters or form clean method
Quick question. I'm trying yo access one of the fields of a model using a variable.
class ExampleModel(models.Model):
the_field = models.CharField()
the_field_two = models.CharField()
How would access the field dynamically? I tried:
model = ExampleModel.objects.get(pk=1)
fieldtoget = 'the_field'
test_var = model[fieldtoget]
But it doesn't seem to work, any ideas how I would do this?
Update: Thought I'd update my question. I'm trying to write a function (as part of larger function) that can not only get the value of the field but also update it from a variable fieldname. For example:
model[fieldtoget] = 'yo'
model.save()
In PHP you can use the {} wrapper - $model{$fieldtoget} - as an example, for dynamic variable names was hoping there was something similar in python :)
Cheers
You can use pythons getattr function to do this. Pass the field name in as the attribute.
getattr(model, fieldtoget)
Since fieldtoget is a variable, this is dynamic.
You can use setattr to set it the same way.
I feel that this is a very simple question, but I'm new to Python, and I'm learning Django at the same time.
My objective is to create a string dictionary representation i.e. it's dictionary formatted but a string, of a Model's instance in Django. How could I do that? Is there a built-in function that I can call straight from the object's instance, or do I have to define one?
UPDATE:
I would like to call this functionality within the model definition itself i.e. I'm implementing a class method or function which needs this functionality. I'm thinking of a functionality which behaves like python's built-in function locals() but should only return the model's attributes.
I also would like to add that I'll be calling this functionality on a model's instance which has not been saved yet to the database. So in essence, I'll be working on a model's instance representing a record which is not yet in the database. So anything function using a Manager or QuerySet I guess is not why I'm looking for.
Example:
class Person(models.Model):
name = ...
age = ...
def func_doing_something(self):
#get the string dictionary representation of this model's instance
#do something to it
#return something
Thanks everyone!
Use p = Person(name='john', age=10).values()
See here: https://docs.djangoproject.com/en/dev/ref/models/querysets/#django.db.models.query.QuerySet.values
To get it to a string use:
s = str(p[0])
You can serialize your objects to json format, e.g. with django build-in serializers
This allows you deserialize quite easily.
I found from this SO post the solution I was looking for...
some Django object obj
[(field.name, getattr(obj,field.name)) for field in obj._meta.fields]
and just call dict() on the result.
I'm interested in subclassing django's ImageFileField to allow access to the image IPTC metadata, something like:
>>> from myapp.models import SomeModel
>>> obj = SomeModel.objects.all()[0] # or what have you
>>> obj.image.iptc['keywords']
('keyword','anotherkeyword','etc')
... the docs say to read over django's internal code, which I did; I've tried to produce a working implementation and I am not sure what I'm doing -- I've defined custom fields before, but I can't come up with boilerplate setup for a file-based field.
I know I need to define an attr_class and a descriptor_class to make it work. Does anyone have a straightforward example or suggestion, with which I could get started?
It's not clear from your question: have you tried something like this?
class ImageMetadataMixin(object):
"""Mixin can be added to any image file"""
#property
def iptc(self):
"""Or something like this"""
class ImageWithMetadataFieldFile(ImageMetadataMixin, ImageFieldFile):
pass
class ImageWithMetadataField(ImageField):
attr_class = ImageWithMetadataFieldFile
I think it's all what necessary. Why do you think you need to redefine descriptor_class?
UPDATE: I have figured this one out -- thanks in part to the answer #valya provided. An example of a successful implementation can be found in my fork of django-imagekit:
https://github.com/fish2000/django-imagekit/blob/icc-develop/imagekit/modelfields.py