使用外键引用保存Django表单

时间:2018-05-01 22:06:41

标签: django django-models django-forms

我有一个引用三个模型的表单,我想将项目保存到每个模型。其中一个模型有其他模型的外键引用,我也想保存它们。

我的模特看起来像:

class Address(models.Model):
    housenumber = models.CharField(max_length=20,default='',blank=True)
    street = models.CharField(max_length=80,default='',blank=True)
    town = models.CharField(max_length=80,default='',blank=True)
    county = models.CharField(max_length=60,default='',blank=True)
    country = models.CharField(max_length=20,default='',blank=True)
    postcode = models.CharField(max_length=10,default='',blank=True)

class GeoLocation(models.Model):
    longitude = models.FloatField(default=-4.2576300)
    latitude = models.FloatField(default=55.8651500)

class Location(models.Model):
    locationname = models.CharField(max_length=80,default='',blank=True)
    address = models.ForeignKey(Address, on_delete=models.CASCADE)
    geolocation = models.ForeignKey(GeoLocation, on_delete=models.CASCADE, default='')

我的观点如下:

        if locationform.is_valid() and addressform.is_valid() and geolocationform.is_valid():
            locationform.save(commit=False)
            new_address = addressform.save()
            new_geolocation = geolocationform.save()
            locationform.address = new_address
            locationform.geolocation = new_geolocation
            locationform.save()

这会给我一个错误,指出“NOT NULL约束失败:location_location.address_id”。

有人可以帮忙吗?我是Django的新手,所以很难找到这些东西。

2 个答案:

答案 0 :(得分:1)

感谢Eduardo我设法让它使用以下代码,几乎和你的一样:

    if locationform.is_valid() and addressform.is_valid() and geolocationform.is_valid():
        new_location = locationform.save(commit=False)
        new_address = addressform.save()
        new_geolocation = geolocationform.save()
        Location.objects.create(
            locationname= new_location.locationname,
            address=new_address,
            geolocation=new_geolocation)

答案 1 :(得分:0)

一种解决方案可能是:

if locationform.is_valid() and addressform.is_valid() and geolocationform.is_valid():
        new_address = addressform.save()
        new_geolocation = geolocationform.save()
        locationform.address = new_address
        locationform.geolocation = new_geolocation
        Location.objects.create(
            locationname=locationform.data.get('locationname', " ",
            address=new_address,
            geolocation=new_geolocation)