0

これらのモデルを前提として、FinancialTransactionが複数のThingに割り当てられるのを防ぐにはどうすればよいですか?

つまり、ThingOneにFinancialTransactionがある場合、ThingTwoまたはThingThreeはそれと関係を持つことができません。

管理者でこれを強制するにはどうすればよいですか?もちろん、Inlinesを使用してSomeThing管理者でThing *を取得することはできますが、これにより、複数のThing*を設定できます。

私の最初の傾向は、私のモデリングが間違っていて、すべてのモノを1つのモデルで表現する必要があるということですが、それらは間違いなく異なるタイプのモノです。

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 つの場所に存在し、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 に答える