简体   繁体   English

在 django 管理员中任意设置 ManyToMany 字段的位置/顺序?

[英]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?我正在考虑在联结表中设置 position 字段,在数据库中手动添加它是唯一的方法吗? I'm fairly new to Django and I'm sorry in advance if this happens to be just a basic question.我对 Django 相当陌生,如果这恰好只是一个基本问题,我很抱歉。

Usual ManyToMany doesn't work here, because association table should contain order.通常的ManyToMany在这里不起作用,因为关联表应该包含顺序。 So, this case you have to bring through to the mix:所以,在这种情况下,你必须through混合:

class Gallery(models.Model):
    medias = models.ManyToManyField('Media',related_name='medias', through='ChildGallery')

Where ChildGallery is a join model:其中ChildGallery是一个连接 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.我不知道你想如何实现 order,但如果它只是一个数字,你可以使用IntegerField ,如上所示。

PS Note I wrapped all association models in quotes (like 'Child' not Child ). PS 注意我将所有关联模型都用引号括起来(例如'Child'而不是Child )。 It allows to break circular dependencies, so I recommend to use this way它允许打破循环依赖,所以我建议使用这种方式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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