Django模型/表单 - 获取现有模型并与另一个模型关联

时间:2012-05-09 02:32:06

标签: django django-models django-forms django-views

说我有

class Address(models.Model):
    street = models.CharField()
    postal_code = models.CharField()

class Person(models.Model):
    name = models.CharField()
    address = models.ForeignKey('Address')

如何使用postal_code获取预先存在的Address,然后将其分配给新的Person

我想如果我在插入新的Address时也明白了如何操作但是 - 如何在保存Address之前获取Person? (有postal_code验证和所有)

1 个答案:

答案 0 :(得分:0)

我认为你不想在外键的地址周围 这是你的意思吗?

if request.method == 'POST':
    form = YourForm(request.POST)
    if form.is_valid():
        address = Address.objects.get(postal_code=form.cleaned_data["postal_code"])
        Person(someStreetVar, address)
        Person.save()