python 如何在 Django 中使用动态外键?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/881792/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 21:03:07  来源:igfitidea点击:

How to use dynamic foreignkey in Django?

pythondjangoforeign-keys

提问by Anakin

I want to connect a single ForeignKeyto two different models.

我想将一个连接ForeignKey到两个不同的模型。

For example:

例如:

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

我有两个名为Castsand 的模型Articles,以及第三个模型Faves,用于偏爱其他模型中的任何一个。我怎样才能使ForeignKey动态?

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)

Is this possible?

这可能吗?

回答by vikingosegundo

Here is how I do it:

这是我如何做到的:

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)

You would add something like

你会添加类似的东西

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

to Faves and

到最爱和

    fields.GenericRelation(Faves)

to Article and Cast

文章和演员

contenttypes docs

内容类型文档

回答by S.Lott

Here's an approach. (Note that the models are singular, Django automatically pluralizes for you.)

这是一个方法。(请注意,模型是单数,Django 会自动为您复数。)

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

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

FAVE_CHOICES = ( 
    ('A','Article'),
    ('C','Cast'),
)
class Fave(models.Model):
    type_of_fave = models.CharField( max_length=1, choices=FAVE_CHOICES )
    cast = models.ForeignKey(Casts,null=True)
    article= models.ForeigKey(Articles,null=True)
    user = models.ForeignKey(User,unique=True)

This rarely presents profound problems. It may require some clever class methods, depending on your use cases.

这很少会带来深刻的问题。它可能需要一些巧妙的类方法,具体取决于您的用例。