Django形成新的外键记录

时间:2015-10-16 05:28:57

标签: django

我想为用户的位置提供charfield,如果已经存在,请使用foreignkey。如果它不存在,请创建一个新记录并使用foreignkeycharfield正在选择现有行或创建新行的用户应完全透明。是否有内置功能,还是必须在view.py中创建?

解决方案:

views.py

    place, created = Place.objects.get_or_create(
        street_number = form.cleaned_data['street_number'],
        route = Route.objects.get_or_create(
            route = form.cleaned_data['route'],
            neighborhood = Neighborhood.objects.get_or_create(
                neighborhood = form.cleaned_data['neighborhood'],
                locality = Locality.objects.get_or_create(
                    locality = form.cleaned_data['locality'],
                    administrative_area_level_1 = form.cleaned_data['administrative_area_level_1']
                )[0]
            )[0]
        )[0]
    )

1 个答案:

答案 0 :(得分:0)

ModelForm中做起来并不难。您只需覆盖ModelForm.save()

def save(self, commit=True):
    if not commit:
        raise NotImplementedException('commit=False is not supported yet')

    super(MyModelForm, self).save(commit=commit)

    ZipCode.objects.get_or_create(zipcode=self.instance.zipcode)

    return self.instance