2012-12-28 56 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