Django:将对象添加到相关集中而不保存到数据库 [英] Django: Adding objects to a related set without saving to DB

查看:108
本文介绍了Django:将对象添加到相关集中而不保存到数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在应用程序中编写内部API,而不必将其与数据库耦合。

I'm trying to write an internal API in my application without necessarily coupling it with the database.

class Product(models.Model):
    name=models.CharField(max_length=4000)
    price=models.IntegerField(default=-1)
    currency=models.CharField(max_length=3, default='INR')

class Image(models.Model): 
    # NOTE -- Have changed the table name to products_images
    width=models.IntegerField(default=-1)
    height=models.IntegerField(default=-1)
    url=models.URLField(max_length=1000, verify_exists=False)
    product=models.ForeignKey(Product)

def create_product:
    p=Product()
    i=Image(height=100, widght=100, url='http://something/something')
    p.image_set.add(i)
    return p

现在,当我调用create_product()时,Django抛出一个错误:

Now, when I call create_product() Django throws up an error:

IntegrityError: products_images.product_id may not be NULL

但是,如果我调用p.save()& i.save()在调用p.image_set.add(i)之前起作用。有什么方法可以将对象添加到相关对象集中而无需先将它们都保存到数据库中?

However, if I call p.save() & i.save() before calling p.image_set.add(i) it works. Is there any way that I can add objects to a related object set without saving both to the DB first?

推荐答案

def create_product():
    product_obj = Product.objects.create(name='Foobar')
    image_obj = Image.objects.create(height=100, widght=100, url='http://something/something', product=product_obj)
    return product_obj

说明
必须先创建产品对象,然后将其分配给Image对象,因为此处的id和name是必填字段。

Explanation: Product object has to be created first and then assign it to the Image object because id and name here is required field.

我想知道为什么您不要求在第一种情况下在DB中输入产品?如果有任何特定原因,那么我可能建议您解决一些问题?

I am wondering why wouldn't you not require to make a product entry in DB in first case? If there is any specific reason then i may suggest you some work around?

编辑:好的!我想我了解您,您不希望最初将产品分配给图像对象。如何将产品字段创建为null等于true。

Okay! i think i got you, you don't want to assign a product to an image object initially. How about creating a product field as null is equal to true.

product = models.ForeignKey(Product, null=True)

现在,您的函数变为:

def create_product():
        image_obj = Image.objects.create(height=100, widght=100, url='http://something/something')
        return image_obj

希望对您有帮助吗?

这篇关于Django:将对象添加到相关集中而不保存到数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆