0

我有一些模型:

Tag(models.Model):
    name = models.CharField()
Tag2(models.Model):
    name = models.CharField()

Blog(models.Model):
    name = models.CharField()
    tag = models.ManyToMany(Tag)
    tag2 = models.ManyToMany(Tag2)

Author(models.Model):
    name = models.CharField()
    tag = models.ManyToManyField(Tag)
    tag2 = models.ManyToManyField(Tag2)

SomeOtherModel1(models.Model):
    name = models.CharField()
    tag = models.ManyToManyField(Tag)
    tag2 = models.ManyToManyField(Tag2)

SomeOtherModel2(models.Model):
    someothermodel1 = models.ManyToManyField(SomeOtherModel1)
    tag2 = models.ManyToManyField(Tag2)

Post(models.Model):
    name = models.CharField()
    tag = models.ManyToMany(Tag)
    tag2 = models.ManyToMany(Tag2)
    author = models.ManyToMany(Author)
    blog = models.ForeignKey(Blog)
    someothermodel = models.ForeignKeyField(SomeOtherModel2)

我需要收集元素的所有标签和 tag2(来自博客、作者和所有其他相关对象)Post。将来我打算添加其他模型

怎么做?

我目前的解决方案是:

AbstractModel(models.Model)
    class Meta:
        abstract = True
    def tags(self, add_self=True):
        try: result = self.tag.all() if add_self else Tag.objects.none()
        except: result = Tag.objects.none()
        for fieldname in self._meta.get_all_field_names():
            try: result |= reduce(or_, [child.tags() for child in self._meta.get_field(fieldname).value_from_object(self)])
            except: pass
        return result
    def tag2s(self, add_self=True):
        try: result = self.tag2.all() if add_self else Tag2.objects.none()
        except: result = Tag2.objects.none()
        for fieldname in self._meta.get_all_field_names():
            try: result |= reduce(or_, [child.tag2s() for child in self._meta.get_field(fieldname).value_from_object(self)])
            except: pass
        return result

Author(AbstractModel)
    ...
SomeOtherModel1(AbstractModel)
    ...
SomeOtherModel2(AbstractModel)
    ...
Post(AbstractModel)
    ...

我认为这个解决方案很丑陋。如何让它美丽?如何在不使用附加功能(tag2s,tag3s,...等)的情况下制作它,如下所示:

class AbstractModel(models.Model):
    def getRelatedObjects(fieldname='tag', add_self=True):
4

0 回答 0