如何在 Django 中使用动态外键? [英] How to use dynamic foreignkey in Django?

查看:30
本文介绍了如何在 Django 中使用动态外键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将单个 ForeignKey 连接到两个不同的模型.

I want to connect a single ForeignKey to two different models.

例如:

我有两个名为 CastsArticles 的模型,还有第三个模型 Faves,用于收藏其他模型中的任何一个.如何使 ForeignKey 动态化?

I have two models named Casts and Articles, and a third model, Faves, for favoriting either of the other models. How can I make the ForeignKey dynamic?

class Articles(models.Model):
    title = models.CharField(max_length=100)
    body = models.TextField()

class Casts(models.Model):
    title = models.CharField(max_length=100)
    body = models.TextField()

class Faves(models.Model):
    post = models.ForeignKey(**---CASTS-OR-ARTICLES---**)
    user = models.ForeignKey(User,unique=True)

这可能吗?

推荐答案

我是这样做的:

from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import fields


class Photo(models.Model):
    picture = models.ImageField(null=True, upload_to='./images/')
    caption = models.CharField(_("Optional caption"),max_length=100,null=True, blank=True)

    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = fields.GenericForeignKey('content_type', 'object_id')

class Article(models.Model):
    ....
    images     = fields.GenericRelation(Photo)

你会添加类似的东西

    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = fields.GenericForeignKey('content_type', 'object_id')

致最爱和

    fields.GenericRelation(Faves)

到文章和演员

contenttypes 文档

这篇关于如何在 Django 中使用动态外键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆