Django: a one-to-many relationship with Contenttypes

I am trying to do the following in Django ORM. The presence of a model Publishthat controls the publication of various types of content (other models). That way, I can easily make Publish.objects.all()and sort them by date. I made a general model as follows:

class Publish(models.Model):
    """ Intermediary model for displaying and managing different types of content """
    status = models.IntegerField(_('status'), choices=STATUS_CHOICES, default=1)
    publish = models.DateTimeField(_('publish'), default=datetime.datetime.now)

    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey('content_type', 'object_id')

The problem is that I want to attach this to various models. It should be an attitude OneToMany. Because an article can have only one publication date. The general attitude is, as far as I know, the attitude ManyToMany.

I tried to limit max_numand extrain GenericTabularInlinein admin.py, but this is not a great working solution. Does anyone know how to attach a publication model to several different models, making them a one-to-many relationship? Many of them are Publish models, one of which is ex. Article.

+3
source share
3 answers

Your guess is wrong. Shared foreign keys are from one to many, not many to many. You can see that your model has fields content_objectand object_id- that is, this Publish instance is associated with one target, although this object can have many publication instances.

, , , OneToOne. , , Publish, . , unique_together content_type object_id Meta.

class Publish(models.Model):
    ... fields ...

    class Meta:
        unique_together('content_type', 'object_id')

, , , , , , .

+7

OneToOneGenericForeignKey, .

, ( ) , .

, , (, ), max_num/field/save/manager/whatever .

0

(, , - ), , OneToOne, OneToMany ( Publish , ). GenericForeignKey , ForeignKey . DRY, , .

0

Source: https://habr.com/ru/post/1724861/


All Articles