Django如何覆盖'get_or_create'来创建父对象(如果它不存在)

时间:2014-01-18 14:57:45

标签: python django

models.py

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中执行此操作。

1 个答案:

答案 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')