The contenttypes frameworkLink para este cabeçalho
Django includes a contenttypes application that can
track all of the models installed in your Django-powered project, providing a
high-level, generic interface for working with your models.
Visão GeralLink para este cabeçalho
At the heart of the contenttypes application is the
ContentType model, which lives at
django.contrib.contenttypes.models.ContentType. Instances of
ContentType represent and store
information about the models installed in your project, and new instances of
ContentType are automatically
created whenever new models are installed.
Instances of ContentType have
methods for returning the model classes they represent and for querying objects
from those models. ContentType
also has a custom manager that adds methods for
working with ContentType and for
obtaining instances of ContentType
for a particular model.
Relations between your models and
ContentType can also be used to
enable “generic” relationships between an instance of one of your
models and instances of any model you have installed.
Installing the contenttypes frameworkLink para este cabeçalho
The contenttypes framework is included in the default
INSTALLED_APPS list created by django-admin startproject,
but if you’ve removed it or if you manually set up your
INSTALLED_APPS list, you can enable it by adding
'django.contrib.contenttypes' to your INSTALLED_APPS setting.
It’s generally a good idea to have the contenttypes framework installed; several of Django’s other bundled applications require it:
The admin application uses it to log the history of each object added or changed through the admin interface.
Django’s
authentication frameworkuses it to tie user permissions to specific models.
The ContentType modelLink para este cabeçalho
- class ContentTypeLink para esta definição
Each instance of
ContentTypehas two fields which, taken together, uniquely describe an installed model:- app_labelLink para esta definição
The name of the application the model is part of. This is taken from the
app_labelattribute of the model, and includes only the last part of the application’s Python import path;django.contrib.contenttypes, for example, becomes anapp_labelofcontenttypes.
- modelLink para esta definição
The name of the model class.
Additionally, the following property is available:
- nameLink para esta definição
The human-readable name of the content type. This is taken from the
verbose_nameattribute of the model.
Let’s look at an example to see how this works. If you already have
the contenttypes application installed, and then add
the sites application to your
INSTALLED_APPS setting and run manage.py migrate to install it,
the model django.contrib.sites.models.Site will be installed into
your database. Along with it a new instance of
ContentType will be
created with the following values:
Methods on ContentType instancesLink para este cabeçalho
Each ContentType instance has
methods that allow you to get from a
ContentType instance to the
model it represents, or to retrieve objects from that model:
- ContentType.get_object_for_this_type(**kwargs)Link para esta definição
Takes a set of valid lookup arguments for the model the
ContentTyperepresents, and doesa get() lookupon that model, returning the corresponding object.
- ContentType.model_class()Link para esta definição
Returns the model class represented by this
ContentTypeinstance.
For example, we could look up the
ContentType for the
User model:
>>> from django.contrib.contenttypes.models import ContentType
>>> ContentType.objects.get(app_label="auth", model="user")
<ContentType: user>
And then use it to query for a particular
User, or to get access
to the User model class:
>>> user_type.model_class()
<class 'django.contrib.auth.models.User'>
>>> user_type.get_object_for_this_type(username='Guido')
<User: Guido>
Together,
get_object_for_this_type()
and model_class() enable
two extremely important use cases:
Using these methods, you can write high-level generic code that performs queries on any installed model – instead of importing and using a single specific model class, you can pass an
app_labelandmodelinto aContentTypelookup at runtime, and then work with the model class or retrieve objects from it.You can relate another model to
ContentTypeas a way of tying instances of it to particular model classes, and use these methods to get access to those model classes.
Several of Django’s bundled applications make use of the latter technique.
For example,
the permissions system in
Django’s authentication framework uses a
Permission model with a foreign
key to ContentType; this lets
Permission represent concepts like
“can add blog entry” or “can delete news story”.
O ContentTypeManagerLink para este cabeçalho
- class ContentTypeManagerLink para esta definição
ContentTypealso has a custom manager,ContentTypeManager, which adds the following methods:- clear_cache()Link para esta definição
Clears an internal cache used by
ContentTypeto keep track of models for which it has createdContentTypeinstances. You probably won’t ever need to call this method yourself; Django will call it automatically when it’s needed.
- get_for_id(id)Link para esta definição
Lookup a
ContentTypeby ID. Since this method uses the same shared cache asget_for_model(), it’s preferred to use this method over the usualContentType.objects.get(pk=id)
- get_for_model(model, for_concrete_model=True)Link para esta definição
Takes either a model class or an instance of a model, and returns the
ContentTypeinstance representing that model.for_concrete_model=Falseallows fetching theContentTypeof a proxy model.
- get_for_models(*models, for_concrete_models=True)Link para esta definição
Takes a variadic number of model classes, and returns a dictionary mapping the model classes to the
ContentTypeinstances representing them.for_concrete_models=Falseallows fetching theContentTypeof proxy models.
- get_by_natural_key(app_label, model)Link para esta definição
Returns the
ContentTypeinstance uniquely identified by the given application label and model name. The primary purpose of this method is to allowContentTypeobjects to be referenced via a natural key during deserialization.
The get_for_model() method is especially
useful when you know you need to work with a
ContentType but don’t
want to go to the trouble of obtaining the model’s metadata to perform a manual
lookup:
>>> from django.contrib.auth.models import User
>>> ContentType.objects.get_for_model(User)
<ContentType: user>
Relações genéricasLink para este cabeçalho
Adding a foreign key from one of your own models to
ContentType allows your model to
effectively tie itself to another model class, as in the example of the
Permission model above. But it’s possible
to go one step further and use
ContentType to enable truly
generic (sometimes called “polymorphic”) relationships between models.
A simple example is a tagging system, which might look like this:
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models
class TaggedItem(models.Model):
tag = models.SlugField()
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
def __str__(self):
return self.tag
A normal ForeignKey can only “point
to” one other model, which means that if the TaggedItem model used a
ForeignKey it would have to
choose one and only one model to store tags for. The contenttypes
application provides a special field type (GenericForeignKey) which
works around this and allows the relationship to be with any
model:
- class GenericForeignKeyLink para esta definição
There are three parts to setting up a
GenericForeignKey:Give your model a
ForeignKeytoContentType. The usual name for this field is “content_type”.Give your model a field that can store primary key values from the models you’ll be relating to. For most models, this means a
PositiveIntegerField. The usual name for this field is “object_id”.Give your model a
GenericForeignKey, and pass it the names of the two fields described above. If these fields are named “content_type” and “object_id”, you can omit this – those are the default field namesGenericForeignKeywill look for.
- for_concrete_modelLink para esta definição
If
False, the field will be able to reference proxy models. Default isTrue. This mirrors thefor_concrete_modelargument toget_for_model().
This will enable an API similar to the one used for a normal
ForeignKey;
each TaggedItem will have a content_object field that returns the
object it’s related to, and you can also assign to that field or use it when
creating a TaggedItem:
>>> from django.contrib.auth.models import User
>>> guido = User.objects.get(username='Guido')
>>> t = TaggedItem(content_object=guido, tag='bdfl')
>>> t.save()
>>> t.content_object
<User: Guido>
If the related object is deleted, the content_type and object_id fields
remain set to their original values and the GenericForeignKey returns
None:
>>> guido.delete()
>>> t.content_object # returns None
Due to the way GenericForeignKey
is implemented, you cannot use such fields directly with filters (filter()
and exclude(), for example) via the database API. Because a
GenericForeignKey isn’t a
normal field object, these examples will not work:
# This will fail
>>> TaggedItem.objects.filter(content_object=guido)
# This will also fail
>>> TaggedItem.objects.get(content_object=guido)
Likewise, GenericForeignKeys
does not appear in ModelForms.
Reverse generic relationsLink para este cabeçalho
- class GenericRelationLink para esta definição
The relation on the related object back to this object doesn’t exist by default. Setting
related_query_namecreates a relation from the related object back to this one. This allows querying and filtering from the related object.
If you know which models you’ll be using most often, you can also add a “reverse” generic relationship to enable an additional API. For example:
from django.contrib.contenttypes.fields import GenericRelation
from django.db import models
class Bookmark(models.Model):
url = models.URLField()
tags = GenericRelation(TaggedItem)
Bookmark instances will each have a tags attribute, which can
be used to retrieve their associated TaggedItems:
>>> b = Bookmark(url='https://www.djangoproject.com/')
>>> b.save()
>>> t1 = TaggedItem(content_object=b, tag='django')
>>> t1.save()
>>> t2 = TaggedItem(content_object=b, tag='python')
>>> t2.save()
>>> b.tags.all()
<QuerySet [<TaggedItem: django>, <TaggedItem: python>]>
Defining GenericRelation with
related_query_name set allows querying from the related object:
tags = GenericRelation(TaggedItem, related_query_name='bookmarks')
This enables filtering, ordering, and other query operations on Bookmark
from TaggedItem:
>>> # Get all tags belonging to bookmarks containing `django` in the url
>>> TaggedItem.objects.filter(bookmarks__url__contains='django')
<QuerySet [<TaggedItem: django>, <TaggedItem: python>]>
Of course, if you don’t add the reverse relationship, you can do the same types of lookups manually:
>>> b = Bookmark.objects.get(url='https://www.djangoproject.com/')
>>> bookmark_type = ContentType.objects.get_for_model(b)
>>> TaggedItem.objects.filter(content_type__pk=bookmark_type.id, object_id=b.id)
<QuerySet [<TaggedItem: django>, <TaggedItem: python>]>
Just as GenericForeignKey
accepts the names of the content-type and object-ID fields as
arguments, so too does
GenericRelation;
if the model which has the generic foreign key is using non-default names
for those fields, you must pass the names of the fields when setting up a
GenericRelation to it. For example, if the TaggedItem model
referred to above used fields named content_type_fk and
object_primary_key to create its generic foreign key, then a
GenericRelation back to it would need to be defined like so:
tags = GenericRelation(
TaggedItem,
content_type_field='content_type_fk',
object_id_field='object_primary_key',
)
Note also, that if you delete an object that has a
GenericRelation, any objects
which have a GenericForeignKey
pointing at it will be deleted as well. In the example above, this means that
if a Bookmark object were deleted, any TaggedItem objects pointing at
it would be deleted at the same time.
Unlike ForeignKey,
GenericForeignKey does not accept
an on_delete argument to customize this
behavior; if desired, you can avoid the cascade-deletion simply by not using
GenericRelation, and alternate
behavior can be provided via the pre_delete
signal.
Generic relations and aggregationLink para este cabeçalho
Django’s database aggregation API works with a
GenericRelation. For example, you
can find out how many tags all the bookmarks have:
>>> Bookmark.objects.aggregate(Count('tags'))
{'tags__count': 3}
Generic relation in formsLink para este cabeçalho
The django.contrib.contenttypes.forms module provides:
A formset factory,
generic_inlineformset_factory(), for use withGenericForeignKey.
- class BaseGenericInlineFormSetLink para esta definição
- generic_inlineformset_factory(model, form=ModelForm, formset=BaseGenericInlineFormSet, ct_field='content_type', fk_field='object_id', fields=None, exclude=None, extra=3, can_order=False, can_delete=True, max_num=None, formfield_callback=None, validate_max=False, for_concrete_model=True, min_num=None, validate_min=False)Link para esta definição
Returns a
GenericInlineFormSetusingmodelformset_factory().You must provide
ct_fieldandfk_fieldif they are different from the defaults,content_typeandobject_idrespectively. Other parameters are similar to those documented inmodelformset_factory()andinlineformset_factory().The
for_concrete_modelargument corresponds to thefor_concrete_modelargument onGenericForeignKey.
Generic relations in adminLink para este cabeçalho
O módulo django.contrib.contenttypes.admin provê GenericTabularInline e GenericStackedInline (subclasses de GenericInlineModelAdmin)
These classes and functions enable the use of generic relations in forms and the admin. See the model formset and admin documentation for more information.
- class GenericInlineModelAdminLink para esta definição
The
GenericInlineModelAdminclass inherits all properties from anInlineModelAdminclass. However, it adds a couple of its own for working with the generic relation:- ct_fieldLink para esta definição
The name of the
ContentTypeforeign key field on the model. Defaults tocontent_type.
- ct_fk_fieldLink para esta definição
The name of the integer field that represents the ID of the related object. Defaults to
object_id.
- class GenericTabularInlineLink para esta definição
- class GenericStackedInlineLink para esta definição
Subclasses of
GenericInlineModelAdminwith stacked and tabular layouts, respectively.