2014-01-18 36 views
1

models.py的Django如何重写“get_or_create”创建父对象,如果不存在

class Country(models.Model): 

    code = models.CharField(max_length=2, unique=True) 
    name = models.CharField(max_length=100) 

    def __unicode__(self): 
     return self.name 

    class Meta: 
     verbose_name_plural = 'countries' 


class State(models.Model): 

    country = models.ForeignKey(Country) 
    code = models.CharField(max_length=5) 
    name = models.CharField(max_length=40) 

    def __unicode__(self): 
     return self.name 

我希望能够做这样的事情吧:

state, created = State.objects.get_or_create(name='myState',code='myCode', 
         country__code='myCountryCode', 
         country__name='myCountryName') 

现在,我的解决方案(实际上没有试过没):

class StateManager(models.Manager): 

    def get_or_create(self, **kwargs): 
     country_data = {} 
     for key, value in kwargs.iteritems(): 
      if key.startswith('country__'): 
       country_data[key.replace('country__', '')] = value 
     #will this work? 
     country, created = Country.objects.get_or_create(country_data) 
     #get_or_create needs to be called here excluding 'country__' arguments 
     #and adding the 'country' object 
     super(StateManager, self).get_or_create(modified_kwargs) 

如果试图使之前在Django 1.6这样做的更好的办法,我想此代码工作。

+0

创建父对象然后创建子对象有什么问题? –

回答

2

您的解决方案将引入一堆错误/异常来源。为什么不按照标准程序?

country, created = Country.objects.get_or_create(name='myCountryName', code='myCountryCode') 
state, created = State.objects.get_or_create(country=country, name='myStateName', code='myStateCode') 
+0

是的,我知道它有点棘手......只是想知道是否有一种以“反向级联”创建风格创建父对象的方法..但我同意你的看法,这太复杂了,两行代码的代码要简单得多。 – martincho

相关问题