A
A
Andrey Salnikov2017-05-19 09:00:38
Django
Andrey Salnikov, 2017-05-19 09:00:38

How to set only 2 models in ContentType?

There is this model:

class Slider(models.Model):
    name = models.CharField(max_length=200, verbose_name='Название')
    image = models.ImageField(upload_to='slider', verbose_name='Изображение')
    content = models.TextField(verbose_name='Текст на слайдере')
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = 'Слайдер'
        verbose_name_plural = 'Слайдеры'

Accordingly, in the field - content_type = models.ForeignKey(ContentType) all models are displayed. And I only need 2.
Accordingly, I have 2 questions.
1) How to do as I described.
2) Is it possible to select already existing elements from the selected Model in the object_id field?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Burnaev, 2017-05-19
@Shshzik

By itself, content_type as a foreign key to any table does not imply any restrictions ... since you are essentially specifying the ID of the type you are referring to (link to the content_type table) and the id of the object itself ....
But you can make a restriction at the form display level where you select one or another model for
the link ... you want to work...
If you don't use the admin panel, but custom forms (or a custom form for the admin panel) - I advise you to simply impose a restriction on the queryset that is issued in the content_type field

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question