如何得到所有相关的对象

时间:2013-10-28 08:52:54

标签: python django django-models many-to-many

我有一些模特:

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)

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

如何制作?

我目前的解决方案是:

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):

0 个答案:

没有答案