How to work with unsaved many-to-many relations in django?

前端 未结 3 1164
孤街浪徒
孤街浪徒 2021-01-12 23:51

I have a couple of models in django which are connected many-to-many. I want to create instances of these models in memory, present them to the user (via custom met

3条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-13 00:19

    Very late answer, but wagtail's team has made a separate Django extension called django-modelcluster. It's what powers their CMS's draft previews.

    It allows you to do something like this (from their README):

    from modelcluster.models import ClusterableModel
    from modelcluster.fields import ParentalKey
    
    class Band(ClusterableModel):
        name = models.CharField(max_length=255)
    
    class BandMember(models.Model):
        band = ParentalKey('Band', related_name='members')
        name = models.CharField(max_length=255)
    

    Then the models can be used like so:

    beatles = Band(name='The Beatles')
    beatles.members = [
        BandMember(name='John Lennon'),
        BandMember(name='Paul McCartney'),
    ]
    

    Here, ParentalKey is the replacement for Django's ForeignKey. Similarly, they have ParentalManyToManyField to replace Django's ManyToManyField.

提交回复
热议问题