Reputation: 73
I have the below models:
# Child
class Media (models.Model):
id = models.BigAutoField(primary_key=True)
name = models.CharField(max_length=128,unique=True)
file = models.FileField()
enabled = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.name
# Parent
class Gallery(models.Model):
id = models.BigAutoField(primary_key=True)
name = models.CharField(max_length=128,unique=True)
description = models.TextField(max_length=254,null=True)
medias = models.ManyToManyField(Media,related_name='medias')
enabled = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
verbose_name = "gallery"
verbose_name_plural = "galleries"
def __str__(self):
return self.name
I would like to be able to sort the child table by setting it in junction table; therefore not affecting the child table. I'm thinking of setting position field in junction table, is manually adding it in DB the only way of doing that? I'm fairly new to Django and I'm sorry in advance if this happens to be just a basic question.
Upvotes: 0
Views: 303
Reputation: 15216
Usual ManyToMany
doesn't work here, because association table should contain order. So, this case you have to bring through
to the mix:
class Gallery(models.Model):
medias = models.ManyToManyField('Media',related_name='medias', through='ChildGallery')
Where ChildGallery
is a join model:
class ChildGallery(models.Model):
child = models.ForeignKey(Child)
gallery = models.ForeignKey(Gallery)
order = models.IntegerField()
class Meta:
ordering = ['order']
I don't know how you would like to implement order, but if it's just a number, you could use IntegerField
as I showed above.
P.S. Note I wrapped all association models in quotes (like 'Child'
not Child
). It allows to break circular dependencies, so I recommend to use this way
Upvotes: 0