Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Django如何覆盖';获取或创建';如果父对象不存在,则创建它';不存在_Python_Django - Fatal编程技术网

Python Django如何覆盖';获取或创建';如果父对象不存在,则创建它';不存在

Python Django如何覆盖';获取或创建';如果父对象不存在,则创建它';不存在,python,django,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'

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')
现在,我的解决方案(实际上尚未尝试):


我想知道在Django 1.6中是否有更好的方法来实现这一点,然后再尝试使这段代码正常工作

您的解决方案将引入一系列错误/异常源。为什么不遵循标准程序呢

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

创建父对象然后创建子对象有什么不对?是的,我知道这有点棘手。。。只是想知道是否有一种以“反向级联”创建样式创建父对象的方法。。但我同意你的看法,这太复杂了,两行代码要简单得多。
country, created = Country.objects.get_or_create(name='myCountryName', code='myCountryCode')
state, created = State.objects.get_or_create(country=country, name='myStateName', code='myStateCode')