0

鉴于这些模型,我如何防止将 FinancialTransaction 分配给多个事物?

换句话说,如果 ThingOne 具有 FinancialTransaction,则 ThingTwo 或 ThingThree 不能与它有关系。

如何在管理员中强制执行此操作?我当然可以使用 Inlines 在 SomeThing 管理员中获取 Thing*,但这允许我设置多个 Thing*。

我的第一个倾向是我的建模是错误的,所有事物都应该由一个模型表示,但它们绝对是不同类型的事物。

from django.db import models


class ThingOne(models.Model):
    name = models.CharField(max_length=20)

    some_things = models.ForeignKey('FinancialTransaction', blank = True, null = True)


class ThingTwo(models.Model):
    name = models.CharField(max_length=20)

    some_things = models.ForeignKey('FinancialTransaction', blank = True, null = True)
    thingone = models.ForeignKey(ThingOne)


class ThingThree(models.Model):
    name = models.CharField(max_length=20)

    some_things = models.ForeignKey('FinancialTransaction', blank = True, null = True)
    thingtwo = models.ForeignKey(ThingTwo)


class FinancialTransaction(models.Model):
    value = models.IntegerField()
4

1 回答 1

1

您可以FinancialTransaction使用通用外键建立关系。

https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#id1

from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic

class FinatialTransation(models.Model):
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey('content_type', 'object_id')

那么关系存在于一处,且只能有1处。

然后从FinancialTransaction您检查对象 ID 和对象ContentType并相应地查找它。

ft = FinancialTransaction.objects.get(...)
thing = ft.content_type.get_object_for_this_type(id=ft.object_id)

此外,您可以将 GenericForeignKey 限制为某些内容类型:

class FinatialTransation(models.Model):
    limit = models.Q(
        models.Q(app_label='yourappsname', model='ThingOne') | models.Q(app_label='yourappsname', model='ThingTwo') | models.Q(app_label='yourappsname', model='ThingThree')
    )
    content_type = models.ForeignKey(ContentType, limit_choices_to=limit)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey('content_type', 'object_id')
于 2012-12-29T02:54:53.020 回答