在Queryset.create()方法中使用Django,什么是'self._for_write'?

时间:2018-05-10 00:24:25

标签: python django

在下面的代码中,代码self._for_write是什么意思?

def create(self, **kwargs):
    """
    Create a new object with the given kwargs, saving it to the database
    and returning the created object.
    """
    obj = self.model(**kwargs)
    self._for_write = True
    obj.save(force_insert=True, using=self.db)
    return obj

1 个答案:

答案 0 :(得分:1)

基于django.db.models.query.QuerySet.db

@property
def db(self):
    """Return the database used if this query is executed now."""
    if self._for_write:
        return self._db or router.db_for_write(self.model, **self._hints)
    return self._db or router.db_for_read(self.model, **self._hints)

这意味着当您的 QuerySetself._for_write == True 时,它将使用 db_for_write 触发您的查询。如需了解详情,请阅读Django document db_for_write