django使用F方法更新一個(gè)對(duì)象多個(gè)對(duì)象字段的實(shí)現(xiàn)
通常情況下我們?cè)诟聰?shù)據(jù)時(shí)需要先從數(shù)據(jù)庫(kù)里將原數(shù)據(jù)取出后放在內(nèi)存里,然后編輯某些字段或?qū)傩裕詈筇峤桓聰?shù)據(jù)庫(kù)。使用F方法則可以幫助我們避免將所有數(shù)據(jù)先載入內(nèi)存,而是直接生成SQL語(yǔ)句更新數(shù)據(jù)庫(kù)。
假如我們需要對(duì)所有產(chǎn)品的價(jià)格漲20%,我們通常做法如下。當(dāng)產(chǎn)品很少的時(shí)候,對(duì)網(wǎng)站性能沒(méi)影響。但如果產(chǎn)品數(shù)量非常多,把它們信息全部先載入內(nèi)存會(huì)造成很大性能浪費(fèi)。
products = Product.objects.all()for product in products: product.price *= 1.2 product.save()
使用F方法可以解決上述問(wèn)題。我們直接可以更新數(shù)據(jù)庫(kù),而不必將所有產(chǎn)品載入內(nèi)存。
from django.db.models import F
Product.objects.update(price=F(’price’) * 1.2)
我們也可以使用F方法更新單個(gè)對(duì)象的字段,如下所示:
product = Product.objects.get(pk=5009)product.price = F(’price’) * 1.2product.save()
但值得注意的是當(dāng)你使用F方法對(duì)某個(gè)對(duì)象字段進(jìn)行更新后,需要使用refresh_from_db()方法后才能獲取最新的字段信息(非常重要!)。
如下所示:
product.price = F(’price’) + 1product.save()print(product.price) # <CombinedExpression: F(price) + Value(1)>product.refresh_from_db()print(product.price) # Decimal(’13.00’)
補(bǔ)充知識(shí):Django批量更新多個(gè)屬性
有時(shí)候我們需要同時(shí)(一次性)更新某個(gè)用戶的多條屬性。
1. 用戶model如下:
class User(models.Model): UID = models.CharField(’員工uid’, max_length=200,) name = models.CharField(’員工名字’, max_length=200,) mobile = models.CharField(’手機(jī)號(hào)’, max_length=200,) mail = models.EmailField(u’郵箱’, max_length=200)
2. 用戶的數(shù)據(jù)
user_info = {’UID’: ’ADBES682BOEO’, ’name’: ’張三’, ’mobile’: ’12345678911’, ’mail’: ’test@test.com’ }
3. 新建用戶
User.object.create(UID=’ADBES682BOEO’,name=’張三’,mobile=’12345678911’,mail=’test@test.com’)
這就會(huì)在數(shù)據(jù)庫(kù)中新建一個(gè)張三的數(shù)據(jù)。
4. 更新數(shù)據(jù)
user_info = {’UID’: ’ADBES682BOEO’, ’name’: ’張三2’, ’mobile’: ’12345678912’, ’mail’: ’test2@test.com’ }
4.1 一般的更新操作
user = User.object.get(UID=’ADBES682BOEO’)user.name = user_info[’name’]user.mobile = user_info[’mobile’]user.mail = user_info[’mail’]user.save()
4.2 批量操作
user = User.object.filter(UID=’ADBES682BOEO’)user.update(**user_info)
以上這篇django使用F方法更新一個(gè)對(duì)象多個(gè)對(duì)象字段的實(shí)現(xiàn)就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. ASP中if語(yǔ)句、select 、while循環(huán)的使用方法2. ASP中解決“對(duì)象關(guān)閉時(shí),不允許操作。”的詭異問(wèn)題……3. xml中的空格之完全解說(shuō)4. php bugs代碼審計(jì)基礎(chǔ)詳解5. WMLScript的語(yǔ)法基礎(chǔ)6. ASP使用MySQL數(shù)據(jù)庫(kù)的方法7. msxml3.dll 錯(cuò)誤 800c0019 系統(tǒng)錯(cuò)誤:-2146697191解決方法8. html小技巧之td,div標(biāo)簽里內(nèi)容不換行9. XML入門(mén)的常見(jiàn)問(wèn)題(四)10. ASP動(dòng)態(tài)網(wǎng)頁(yè)制作技術(shù)經(jīng)驗(yàn)分享
