Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Generic relationships and foreign keys are your friend in your path to succeed. Define an intermediate model where one side is generic, then the other side will get a related list of polymorphic models. It's just a little more complicated than a standard m2m join model, in that the generic side has two columns, one to ContentType (actually a FK) and the other to the PK of the actual linked model instance. You can also restrict the models to be linked with using standard FK parameters. You'll get used with it quickly. </p> <p>(now that I get an actual keyboard to write with, here there is the example:)</p> <pre><code>class Post(models.Model): class Meta: abstract = True CONCRETE_CLASSES = ('announcement', 'event',) removed_from = generic.GenericRelation('OwnerRemovedPost', content_type_field='content_type', object_id_field='post_id', ) class Announcement(Post): pass class Event(Post): pass class Owner(models.Model): # non-polymorphic m2m added_events = models.ManyToManyField(Event, null=True) # polymorphic m2m-like property def removed_posts(self): # can't use ManyToManyField with through. # can't return a QuerySet b/c it would be a union. return [i.post for i in self.removed_post_items.all()] def removed_events(self): # using Post's GenericRelation return Event.objects.filter(removed_from__owner=self) class OwnerRemovedPost(models.Model): content_type = models.ForeignKey(ContentType, limit_choices_to={'name__in': Post.CONCRETE_CLASSES}, ) post_id = models.PositiveIntegerField() post = generic.GenericForeignKey('content_type', 'post_id') owner = models.ForeignKey(Owner, related_name='removed_post_items') class Meta: unique_together = (('content_type', 'post_id'),) # to fake FK constraint </code></pre> <p>You can't filter into the related collection like a classic many-to-many, but with the proper methods in <code>Owner</code>, and using the concrete classes' managers smartly, you get everywhere you want.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload