创建动态直通模型

时间:2019-02-27 11:16:51

标签: django django-models

我有很多具有ManyToMany字段的模型。

class Author(Model):
    name = CharField()

class Publication(Model):
    name = CharField()
    authors = ManyToManyField(Author)
    class Meta:
        abstract = True
class Book(Publication):
    pass
class Article(Publication):
    pass
class Journal(Publication):
    pass

class D(Model):
    authors = ManyToManyField(Author)
class E(Model):
    authors = ManyToManyField(Author)

我想将订购字段添加到所有ManyToMany字段中。

自动执行此操作的最佳方法是什么?

尝试。

# Substitution for ManyToMany
class AuthorField(ManyToManyField):
    def __init__(self, **kwargs):

        class Relationship(Model):
            entity = models.ForeignKey(???????????)
            author = models.ForeignKey(Author)
            ordering = models.PositiveSmallIntegerField(default=1)

            class Meta:
                ordering = ('ordering',)

        kwargs['to'] = Author
        kwargs['through'] = Relationship
        super(AuthorField, self).__init__(**kwargs)

1 个答案:

答案 0 :(得分:0)

我找到了方法。

class OrderedManyToManyField(models.ManyToManyField):
    def contribute_to_class(self, cls, name, **kwargs):
        super(OrderedManyToManyField, self).contribute_to_class(cls, name, **kwargs)
        if self.remote_field.through:
            self.remote_field.through.add_to_class('ordering', models.PositiveSmallIntegerField(default=1))
            self.remote_field.through._meta.ordering = ('ordering', )