Django:使用通用关系作为直通模型时返回对象

Django: Returning objects when using a generic relationship as a through model

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

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 到 return 标签对象列表,而不是 through 模型 TaggedItem 对象。

不过,我还想不出最好的方法。有什么想法吗?这是明智的做法吗?

@property
def characteristics(self):
    return Tag.objects.filter(pk__in=self.tag_items.filter(relationship=TaggedItem.CHARACTERISTICS).values('tag'))

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

试试这个:

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