0

我有以下设置,我想用它来标记通用对象(目前只有一种类型,资源对象)。

class Resource(models.Model):
    ...
    tag_items = GenericRelation(TaggedItem, related_query_name='resources')

    @property
    def platform(self):
        return self.tag_items.filter(relationship=TaggedItem.PLATFORM)

    @property
    def characteristics(self):
        return self.tag_items.filter(relationship=TaggedItem.CHARACTERISTICS)


class Tag(models.Model):
    ...


class TaggedItem(models.Model):
    # Relationship choices
    PLATFORM = 'platform'
    CHARACTERISTICS = 'characteristics'
    RELATIONSHIP_CHOICES = (
        (PLATFORM, 'Platform'),
        (CHARACTERISTICS, 'Characteristics'))

    tag = models.ForeignKey(Tag, related_name="%(class)s_items")
    content_type = models.ForeignKey(ContentType, related_name="%(class)s_tagged_items")
    object_id = models.PositiveIntegerField(db_index=True)
    object = GenericForeignKey('content_type', 'object_id')
    relationship = models.CharField(choices=RELATIONSHIP_CHOICES, default=CHARACTERISTICS, max_length=50)

我想要的是resource.platform/characteristics返回标签对象列表,而不是通过模型TaggedItem 对象。

不能完全弄清楚最好的方法来做到这一点。有什么想法吗?这甚至是明智的做法吗?

4

2 回答 2

1

试试这个:

class Resource(models.Model):
    #...
    tag_items = GenericRelation(TaggedItem, related_query_name='resources')

    @property
    def platform(self):
        return Tag.objects.filter(
            taggetitem_items__resources=self,
            taggetitem_items__relationship=TaggedItem.PLATFORM,
        )

    @property
    def characteristics(self):
        return Tag.objects.filter(
            taggetitem_items__resources=self,
            taggetitem_items__relationship=TaggedItem.CHARACTERISTICS,
        )
于 2015-10-14T09:42:42.567 回答
0
@property
def characteristics(self):
    return Tag.objects.filter(pk__in=self.tag_items.filter(relationship=TaggedItem.CHARACTERISTICS).values('tag'))

警告:未经测试的代码可能无法正常工作,但您明白了。

于 2015-10-14T09:27:17.977 回答