简体   繁体   中英

Arbitrarily set position/order of ManyToMany field in django admin?

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.

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.

PS 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM