2012-12-28 54 views
0

鑑於這些模型,我如何防止將FinancialTransaction分配給多個Thing?如何將Django模型限制爲幾種可能的關係之一?

換句話說,如果ThingOne有一個FinancialTransaction,ThingTwo或ThingThree不能與它有關係。

如何在管理員中執行此操作?我當然可以通過Inline在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() 
+0

如果他們是不同類型的東西,那麼爲什麼不能在一個模型的字段例如識別不同的事情鍵入字段 –

+0

它們是具有許多不同字段的完全不同類型的東西。 –

回答

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') 
+0

哦,這很好。這是什麼object_pk? –

+1

對不起,從我的項目中複製並粘貼錯誤。 object_pk == object_id(已更新) – rockingskier