【问题标题】:Django : Multiple possible types in ForeignKey FieldDjango:ForeignKey 字段中的多种可能类型
【发布时间】:2015-08-06 05:03:23
【问题描述】:

我想对以下关系建模,其中 Vehicle owner 字段可以是 Person 或 Company。我们如何在 Django 中做到这一点?

class Person(models.Model):
    name = ...
    other_details = ...

class Company(models.Model):
    name = ...
    other_details = ...

class Vehicle(models.Model):
    owner = models.ForeignKey(x) # 'x' could be a Person or Company

【问题讨论】:

标签: sql django django-models


【解决方案1】:

使用通用外键 例如。

class Vehicle(models.Model):
    content_type = models.ForeignKey(ContentType, null=True, blank=True)
    object_id = models.PositiveIntegerField(null=True, blank=True)
    content_object = generic.GenericForeignKey('content_type', 'object_id')

在保存对象时,您需要获取要为其提供通用 FK 的模型的 content_type 和该模型的对象 ID。

from django.contrib.contenttypes.models import ContentType

content_type = ContentType.objects.get_for_model(Company)
object_id = company_object.id
ve = Vehicle()
ve.content_type = content_type
ve.object_id = object_id
ve.save()

希望这会对你有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    • 2020-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-25
    相关资源
    最近更新 更多