gpt4 book ai didi

python - Django - 使用属性作为外键

转载 作者:行者123 更新时间:2023-12-03 18:34:04 24 4
gpt4 key购买 nike

我的应用程序的数据库已填充并与外部数据源保持同步。我有一个抽象模型,我的 Django 2.2 应用程序的所有模型都来自该模型,定义如下:

class CommonModel(models.Model):
# Auto-generated by Django, but included in this example for clarity.
# id = models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')
ORIGIN_SOURCEA = '1'
ORIGIN_SOURCEB = '2'
ORIGIN_CHOICES = [
(ORIGIN_SOURCEA, 'Source A'),
(ORIGIN_SOURCEB, 'Source B'),
]
object_origin = models.IntegerField(choices=ORIGIN_CHOICES)
object_id = models.IntegerField()

class A(CommonModel):
some_stuff = models.CharField()

class B(CommonModel):
other_stuff = models.IntegerField()
to_a_fk = models.ForeignKey("myapp.A", on_delete=models.CASCADE)

class C(CommonModel):
more_stuff = models.CharField()
b_m2m = models.ManyToManyField("myapp.B")
object_id领域 不能设置为唯一 因为我在应用程序中使用的每个数据源可能都有一个带有 object_id = 1 的对象.因此需要通过字段 object_origin 来追踪对象的起源。 .

不幸的是,Django 的 ORM 不支持多于一列的外键。

问题

在数据库中保留自动生成的主键( id )的同时,我想让我的外键和多对多关系发生在 object_id 上。和 object_origin字段而不是主键 id .

我试过的

我想过做这样的事情:
class CommonModel(models.Model):
# Auto-generated by Django, but included in this example for clarity.
# id = models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')
ORIGIN_SOURCEA = '1'
ORIGIN_SOURCEB = '2'
ORIGIN_CHOICES = [
(ORIGIN_SOURCEA, 'Source A'),
(ORIGIN_SOURCEB, 'Source B'),
]
object_origin = models.IntegerField(choices=ORIGIN_CHOICES)
object_id = models.IntegerField()

def _get_composed_object_origin_id(self):
return f"{self.object_origin}:{self.object_id}"
composed_object_origin_id = property(_get_composed_object_origin_id)

class A(CommonModel):
some_stuff = models.CharField()

class B(CommonModel):
other_stuff = models.IntegerField()
to_a_fk = models.ForeignKey("myapp.A", to_field="composed_object_origin_id", on_delete=models.CASCADE)

但是 Django 提示它:
myapp.B.to_a_fk: (fields.E312) The to_field 'composed_object_origin_id' doesn't exist on the related model 'myapp.A'.
听起来合法,Django 排除了提交给 to_field 的文件。成为数据库字段。但是没有必要在我的 CommonModel中添加一个新字段自 composed_object_type_id使用两个不可为空的字段构建...

最佳答案

您在另一个答案的评论中提到 object_id 不是唯一的,但它与 object_type 的组合是唯一的,所以您可以使用 unique_together 在元类中? IE

class CommonModel(models.Model):
object_type = models.IntegerField()
object_id = models.IntegerField()

class Meta:
unique_together = (
("object_type", "object_id"),
)

关于python - Django - 使用属性作为外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60054350/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com