Что такое content type django

документация Django 3.0

Обзор¶

Взаимосвязь между ContentType и вашими моделями можно использовать для создания «обобщенных» («generic» ) отношений между экземпляром вашей модели и экземпляром любой другой модели в проекте.

Установка и подключение contenttypes¶

Рекомендуется всегда подключать фреймворк контентных типов в проект, поскольку его наличие требуется для работы ряда других встроенных приложений Django:

Модель ContentType ¶

Каждый экземпляр ContentType содержит два поля, которые вместе уникальным образом описывают каждую модель в приложении:

Имя приложения в которое входит данная модель. Данные берутся из атрибута app_label модели и включают в себя только последнюю часть пути, который используется для импорта модели. Н-р, в случае «django.contrib.contenttypes» используется значение атрибута app_label для «contenttypes».

Также доступны следующие свойства:

«Читабельное» имя модели. Берется из атрибута verbose_name модели.

Методы экземпляра ContentType ¶

ContentType. get_object_for_this_type ( ** kwargs

Принимает набор корректных аргументов запроса для модели, представленной данным ContentType и выполняет метод get() этой модели, возвращая соответствующий объект.

Н-р, мы можем получить экземпляр ContentType для модели User следующим образом:

ContentTypeManager ¶

Обобщенные связи(generic relations)¶

Например, так можно реализовать систему тегов:

Существуют три правила по созданию и настройке GenericForeignKey :

Тип первичного ключа

Не существует универсального решения для выбора наилучшего типа поля. Вы должны изучить модели с которыми собираетесь работать, и на основании этого принять решение о выборе типа для поля, руководствуясь принципами эффективности.

Сериализация связей с ContentType

Если связанный объект удален, поля content_type и object_id получат начальные значения и GenericForeignKey вернет None :

Также GenericForeignKey s не отображется в ModelForm s.

Обратная обобщенная связь(reverse generic relations)¶

По умолчанию обратная связь не создается. Чтобы создать такую связь, укажите параметр related_query_name поля. Это позволять получить связанные объекты и использовать поле для фильтрации результатов запроса.

Если модель, с которой предстоит работать наиболее часто, известна заранее, вы можете добавить «обратную» обобщенную связь между моделями и использовать дополнительные возможности API. Н-р:

Это позволяет фильтровать, сортировать и выполнять запросы по Bookmark из TaggedItem :

Обобщенные связи и агрегация¶

Обобщенные связи в формах¶

Обобщенные связи в админке¶

class GenericTabularInline ¶ class GenericStackedInline ¶

Подклассы GenericInlineModelAdmin позволяющие настраивать отображение данных в сложенном(stacked) или табличном(tabular) виде, соответственно.

Источник

Documentation

The contenttypes framework¶

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.

Overview¶

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 framework¶

It’s generally a good idea to have the contenttypes framework installed; several of Django’s other bundled applications require it:

The ContentType model¶

Each instance of ContentType has two fields which, taken together, uniquely describe an installed model:

The name of the application the model is part of. This is taken from the app_label attribute of the model, and includes only the last part of the application’s Python import path; “django.contrib.contenttypes”, for example, becomes an app_label of “contenttypes”.

The name of the model class.

Additionally, the following property is available:

The human-readable name of the content type. This is taken from the verbose_name attribute of the model.

Before Django 1.8, the name property was a real field on the ContentType 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 instances¶

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) [source] ¶

Takes a set of valid lookup arguments for the model the ContentType represents, and does a get() lookup on that model, returning the corresponding object.

Returns the model class represented by this ContentType instance.

For example, we could look up the ContentType for the User model:

Together, get_object_for_this_type() and model_class() enable two extremely important use cases:

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”.

The ContentTypeManager ¶

Clears an internal cache used by ContentType to keep track of models for which it has created ContentType instances. You probably won’t ever need to call this method yourself; Django will call it automatically when it’s needed.

get_for_model (model, for_concrete_model=True) [source] ¶

Takes either a model class or an instance of a model, and returns the ContentType instance representing that model. for_concrete_model=False allows fetching the ContentType of a proxy model.

get_for_models (*models, for_concrete_models=True) [source] ¶

Takes a variadic number of model classes, and returns a dictionary mapping the model classes to the ContentType instances representing them. for_concrete_models=False allows fetching the ContentType of proxy models.

Returns the ContentType instance uniquely identified by the given application label and model name. The primary purpose of this method is to allow ContentType objects 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:

Generic relations¶

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:

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:

There are three parts to setting up a GenericForeignKey :

Primary key type compatibility

The “object_id” field doesn’t have to be the same type as the primary key fields on the related models, but their primary key values must be coercible to the same type as the “object_id” field by its get_db_prep_value() method.

For maximum flexibility you can use a TextField which doesn’t have a maximum length defined, however this may incur significant performance penalties depending on your database backend.

There is no one-size-fits-all solution for which field type is best. You should evaluate the models you expect to be pointing to and determine which solution will be most effective for your use case.

Serializing references to ContentType objects

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 :

Likewise, GenericForeignKey s does not appear in ModelForm s.

Reverse generic relations¶

The relation on the related object back to this object doesn’t exist by default. Setting related_query_name creates 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:

Bookmark instances will each have a tags attribute, which can be used to retrieve their associated TaggedItems :

Defining GenericRelation with related_query_name set allows querying from the related object:

This enables filtering, ordering, and other query operations on Bookmark from TaggedItem :

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:

Of course, if you don’t add the reverse relationship, you can do the same types of lookups manually:

Generic relations and aggregation¶

Generic relation in forms¶

min_num and validate_min were added.

Generic relations in admin¶

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.

The GenericInlineModelAdmin class inherits all properties from an InlineModelAdmin class. However, it adds a couple of its own for working with the generic relation:

Subclasses of GenericInlineModelAdmin with stacked and tabular layouts, respectively.

Источник

Русские Блоги

Django встроенные компоненты-ContentTypes

Django встроенные компоненты-ContentTypes

1. Что такое Django ContentTypes?

Для получения дополнительной информации о ContentTypes вы можете напрямую обратиться к следующим двум ссылкам:

2. Что сделал Django ContentTypes?

При создании проекта django вы можете видеть, что django.contrib.contenttypes уже включен в INSTALL_APPS по умолчанию.

Импортировать компоненты типов содержимого:

Просмотрите содержимое django.contrib.contenttypes.models.ContentType:

Что такое content type django. Смотреть фото Что такое content type django. Смотреть картинку Что такое content type django. Картинка про Что такое content type django. Фото Что такое content type django

Django_content_type записывает текущий проект Django Все приложения, к которым относится модель (Т.е. атрибут app_label) и наименование модели (Т.е. атрибут модели).

1. Интерфейс, предоставляемый экземпляром ContentType

Получить класс модели, представленный текущим типом ContentType

Выполните запрос get, используя класс модели, представленный текущим типом ContentType

2. Интерфейс j, предоставляемый менеджером ContentType (менеджером)

Три, сценарии использования инфраструктуры Django ContentTypes

1. Дизайн-модель

Предположим, мы создали следующую модель, которая содержит курсы степени, специальные курсы и ценовые стратегии.

Ценовая стратегия может быть либо ценовой стратегией тематического курса, либо ценовой стратегией учебного курса. Нужно добавить много ForeignKey в объект ценовой политики.

(1)GenericForeignKey

Django ContentType предоставляет GenericForeignKey Тип, с помощью которого вы можете указать content_object.

(2)GenericRelation

(3) В ценовой политике есть три важных поля

content_type: тип контента, представляющий название модели (например, Course, DegreeCourse)

object_id: идентификатор входящего объекта

content_object: входящий инстанцированный объект, который содержит два атрибута content_type и object_id.

2. Просмотр операции

(1) Добавить данные в таблицу ценовой стратегии (pricepolicy)

После посещения http://127.0.0.1:8000/test/ проверьте данные, сохраненные в таблице ценовой стратегии:

Что такое content type django. Смотреть фото Что такое content type django. Смотреть картинку Что такое content type django. Картинка про Что такое content type django. Фото Что такое content type django

(2) В соответствии с объектом ценовой стратегии найдите соответствующую ему таблицу и данные.

Вот пример просмотра названия курса управления:

(3) Найти все ценовые стратегии, связанные с курсом

Обратите внимание, что здесь необходимо использовать GenericRelation.

Результатом запроса является объект QuerySet. Если вы хотите сделать результат запроса более понятным:

Четыре, краткое содержание ContentType

Если таблица и N таблиц динамически создают отношение внешнего ключа, то при создании внешнего ключа будет создано много столбцов, поэтому многие из них будут пустыми, что приведет к серьезной трате пространства.

Роль компонента ContentType: через два поля (GenericForeignKey, GenericRelation), в случае обеспечения количества столбцов без изменений, пусть таблица и N таблиц связаны внешним ключом.

Источник

Документация Django 1.5.2

Обзор¶

Установка и подключение contenttypes¶

Рекомендуется всегда подключать contenttypes фреймворк в проекте, поскольку его наличие требуется для работы ряда других встроенных приложений Django.

Встроенное приложение администрирования Django использует contenttypes для ведения логов по добавлению или изменению объектов через админку.

Система комментариев Django ( django.contrib.comments ) использует contenttypes для “добавления” комментариев к моделям.

Модель ContentType ¶

Первое, это имя приложения в которое входит данная модель. Данные берутся из атрибута app_label модели и включают в себя только последнюю часть пути, который используется для импорта модели. Н-р, в случае “django.contrib.contenttypes” используется значение атрибута app_label для “contenttypes”.

Методы экземпляра ContentType ¶

The ContentTypeManager ¶

Обобщенные связи(generic relations)¶

Вот простой пример: реализуем систему тэгов(ярлычков), которая могла бы выглядеть так

Существуют три правила по созданию и настройке GenericForeignKey :

Primary key type compatibility

Не существует универсального решения для выбора наилучшего типа поля. Вы должны изучить модели с которыми собираетесь работать, и на основании этого принять решение о выборе типа для поля, руководствуясь принципами эффективности.

Serializing references to ContentType objects

Обратная обобщенная связь(reverse generic relations)¶

Если модель, с которой предстоит работать наиболее часто, известна заранее, вы можете добавить “обратную” обобщенную связь между моделями и использовать дополнительные возможности API. Н-р:

Ну и конечно, если вы не захотите добавить обратную связь, вы можете получить доступ к объекту и “обходным путем”:

Обобщенные связи и агрегация¶

Обобщенные связи в формах и администрировании¶

class GenericTabularInline¶ class GenericStackedInline¶

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

Источник

Документация Django 1.8

Обзор¶

Установка и подключение contenttypes¶

Рекомендуется всегда подключать contenttypes фреймворк в проекте, поскольку его наличие требуется для работы ряда других встроенных приложений Django.

Встроенное приложение администрирования Django использует contenttypes для ведения логов по добавлению или изменению объектов через админку.

Модель ContentType ¶

Первое, это имя приложения в которое входит данная модель. Данные берутся из атрибута app_label модели и включают в себя только последнюю часть пути, который используется для импорта модели. Н-р, в случае “django.contrib.contenttypes” используется значение атрибута app_label для “contenttypes”.

Также доступны следующие свойства:

Методы экземпляра ContentType ¶

The ContentTypeManager ¶

Обобщенные связи(generic relations)¶

Вот простой пример: реализуем систему тэгов(ярлычков), которая могла бы выглядеть так

Существуют три правила по созданию и настройке GenericForeignKey :

Тип первичного ключа

Не существует универсального решения для выбора наилучшего типа поля. Вы должны изучить модели с которыми собираетесь работать, и на основании этого принять решение о выборе типа для поля, руководствуясь принципами эффективности.

Сериализация связей с ContentType

Обратная обобщенная связь(reverse generic relations)¶

По умолчанию обратная связь не создается. Чтобы создать такую связь, укажите параметр related_query_name поля. Это позволять получить связанные объекты и использовать поле для фильтрации результатов запроса.

Если модель, с которой предстоит работать наиболее часто, известна заранее, вы можете добавить “обратную” обобщенную связь между моделями и использовать дополнительные возможности API. Н-р:

Это позволяет фильтровать, сортировать и выполнять запросы по Bookmark из TaggedItem :

Ну и конечно, если вы не захотите добавить обратную связь, вы можете получить доступ к объекту и “обходным путем”:

Обобщенные связи и агрегация¶

Обобщенные связи в формах¶

Обобщенные связи в админке¶

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *