first_obj = MyFirstModel()
second_obj = ImageModel()
first_obj.name = "newname"
first_obj.phonenr = "9898876"
second_obj.image = "new image"
first_obj.save()
first_obj.create(second_obj) #<------ can i do this?
这会保存第二个对象吗?有可能做到这一点吗?
first_obj = MyFirstModel()
second_obj = ImageModel()
first_obj.name = "newname"
first_obj.phonenr = "9898876"
second_obj.image = "new image"
first_obj.save()
first_obj.create(second_obj) #<------ can i do this?
这会保存第二个对象吗?有可能做到这一点吗?
我想你很困惑,试试这个:
class ImageModel(models.Model):
image = models.ImageField()
class MyFirstModel(models.Model):
name = ...
image = models.ForeignKey(Image)
> image_model_instance = ImageModel()
> image_model_instance.save()
> first_model_instance = MyFirstModel(name="foo")
> first_model_instance.image = image_model_instance
> first_model_instance.save()
有一个create()
函数,但它用于创建和保存模型的新实例:
first_model_instance = MyFirstModel.objects.create(Name="foo")
所以和:
first_model_instance = MyFirstModel()
first_model_instance.save()