You need to enable JavaScript to run this app. 如何使用Django GenericForeignKey实现Record关联多类型资源
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Django GenericForeignKey实现Record关联多类型资源

我定义了如下两个模型:

class URLResource(models.Model):
    class ResourceType(models.TextChoices):
        VID = 'VID', _('Video')
        DOC = 'DOC', _('Document')
    
    resource_type = models.CharField(
            choices=ResourceType.choices,
            default=ResourceType.UNK,
            max_length=3)

    title = models.CharField(max_length=280, null=True)
    url = models.URLField()
    created = models.DateTimeField(auto_now_add=True)

    def __repr__(self):
        return f'URLResource {self.resource_type}: {self.title} URL: {self.url}'


class Record(models.Model):
    user = models.ForeignKey(
            settings.AUTH_USER_MODEL, 
            ...)
    date = models.DateTimeField(default=now, blank=True)

    # 这里我想实现指向任意资源的关联

    def __repr__(self):
        return f'Record {{ User: {self.user}, Resource:  }}'

我的业务场景是,大量用户可以创建并查看Record实例,由于底层的URLResource是公共复用的,我原本考虑使用Record到URLResource的多对一关联,保证底层资源可以重复使用。不过目前虽然只有URLResource这一种资源类型,后续我还计划推出VideoResource、PhysicalResource等其他资源类型,显然无法直接使用固定的多对一关联。因此我考虑使用Django的ContentType框架,但始终无法跑通逻辑。

我希望最终能实现至少以下两个需求:

  • 创建Record实例时,可以便捷地为其绑定URLResource(或其他任意资源类型,且每条Record仅关联一个资源)
  • 可以便捷访问关联URLResource的字段,例如通过Record.objects.get(user=x).resource.resource_type这种形式直接获取属性

内容的提问来源于stack exchange,提问作者DaveIdito

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.27 02:45:04