0

我正在尝试使用 Django 的反向通用关系通过 Django 的 ORM 访问和过滤相关对象。请参见下面声明的模型:

from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
from django.contrib.contenttypes.models import ContentType
from django.db import models


class Status(models.Model):
    name = models.CharField(max_length=100)

    def __str__(self):
        return self.name


class Package(models.Model):
    name = models.CharField(max_length=500)
    status = models.ForeignKey(Status, on_delete=models.PROTECT)
    hst_entries = GenericRelation("myapp.StatusHistory", related_query_name="package")

    def __str__(self):
        return self.name


class StatusHistory(models.Model):
    content_type = models.ForeignKey(ContentType, on_delete=models.PROTECT)
    object_id = models.TextField()
    object = GenericForeignKey("content_type", "object_id")
    status = models.ForeignKey(Status, on_delete=models.PROTECT)
    entry_added = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f"{self.content_type} - {self.object_id}: {self.status.name}"

Package如您所见,StatusHistory模型之间存在通用关系。StatusHistory为了从我尝试的模型访问相关包:

StatusHistory.objects.filter(package__name__startswith="pack")

结果:

ProgrammingError: operator does not exist: text = integer
LINE 1: ...kage" ON ("myapp_statushistory"."object_id" = "myapp...
                                                             ^
HINT:  No operator matches the given name and argument types. You might need to add explicit type casts.

我了解 PostgreSQL 抱怨object_idStatusHistory模型)和idPackage模型)字段之间的类型不匹配。这种不匹配可以通过 PostgreSQL cast operator 解决,::如下所示:

### WRONG
join myapp_package on (myapp_statushistory.object_id = my_app_package.id)

### RIGHT
join myapp_package on (myapp_statushistory.object_id = my_app_package.id::varchar)

有没有可能通过 Django 的 ORM 进行这种转换?

注意:object_id字段转换IntegerField为不是我的选择。

4

0 回答 0