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