Agey
Agey

Reputation: 931

Django: Store multiple & dynamically ordered model sequence

Lets say, a user has video clips and images, both of them with their corresponding model, VideoClipModel and ImageModel.

Now i'm adding a new functionality where a user can combine clips and images to create a "final" video. Now what i need is to create a model where i can store the sequence of the video clips and images. Anyone has idea how to to this?

For example: A user wants to create a final video with the following item sequence:

Image1 -> VideoClip1 -> Image2 -> VideoClip2 -> VideoClip3 -> Image3 -> Image1

What i want to do is to create a model where i can store the sequence selected

I though about creating my VideoFinalModel with two m2m fields to ImageModel and VideoClipModel and a charfield which would store the order in a way similar to this:

image_1, video_1, image_2, video_2, video_3, image_3, image_1

So the models would look like:

def VideoFinal(...):
    videos = models.ManyToManyFIeld("VideoClips")
    images = models.ManyToManyFIeld("Images")
    order = models.CharField()

def Images(...):
    """ A bunch of fields here """

def VideoClips(...):
    """ A bunch of different fields here """

Now, this would do what i want... however i dont believe this is how it should be done.

How can i do this in the pythonic way?

Thanks!

Upvotes: 2

Views: 479

Answers (1)

zxzak
zxzak

Reputation: 9446

You could have a model VideoComponent with a position field as well as foreign keys to VideoClipModel and ImageModel. Then a Video model would have a many to many field to VideoComponent.

class Video(models.Model):
    components = models.ManyToManyField('VideoComponent')

class VideoComponent(models.Model):
    image = models.ForeignKey('ImageModel')
    video_clip = models.ForeignKey('VideoClipModel ')
    position = models.IntegerField()

    class Meta:
        ordering = ['position']

Get the ordered components:

 video.components.all()

Also check out django-mptt for storing hierarchical data:

The problem which django-mptt solves.

Project github.

Upvotes: 1

Related Questions