9. class Product():
code = models.CharField(max_length=10, unique=True, db_index=True)
price = models.IntegerField(default=0)
class Product2(models.Model):
category = models.ForeignKey('Category')
service = models.ForeignKey('Service')
price = models.IntegerField(default=0)
class Meta:
unique_together = ('category2', 'service')
index_together = ('category2', 'service')
ѧ 2. ߧէ֧ܧ
10. lines = [
["0001", 10],
["0002", 15],
]
with transaction.atomic():
for line in lines:
Product.objects.filter(
code=line[0]
).update(
price=line[1]
)
ѧ 3. atomic
x1.4
11. ҧߧ ٧ѧ
UPDATE app_product SET price = 3 WHERE code ='0001';
UPDATE app_product SET price = 2 WHERE code ='0002';
ѧ ݧӧڧާ (postgresql)
UPDATE app_product SET price = (CASE
WHEN code = '0001' THEN 3
WHEN code = '0002' THEN 2
ELSE 0
END);
ѧ 4. ѧ ݧӧڧާ
12. ҧߧ ٧ѧ
UPDATE app_product SET price = 3 WHERE code ='0001';
UPDATE app_product SET price = 2 WHERE code ='0002';
ѧ ݧӧڧާ (postgresql)
UPDATE app_product SET price = (CASE
WHEN code = '0001' THEN 3
WHEN code = '0002' THEN 2
ELSE 0
END) WHERE code in ('0001','0002);
ѧ 4. ѧ ݧӧڧާ
13. ҧߧӧݧ֧ߧڧ էߧڧ ٧ѧ
UPDATE app_product SET price = (CASE
WHEN code = '0091' THEN 3 WHEN code = '0092' THEN 3
WHEN code = '0093' THEN 3 WHEN code = '0094' THEN 3
WHEN code = '0095' THEN 3 WHEN code = '0096' THEN 3
WHEN code = '0097' THEN 3 WHEN code = '0098' THEN 3
WHEN code = '0099' THEN 3 WHEN code = '0100' THEN 3
ELSE 0 END
)
WHERE code in
('0091','0092','0093','0094','0095','0096','0097','0098','0099','0100');
ѧ 4. ѧ ݧӧڧާ
x2.5
16. from django.db.models.fields import CharField
from django.db.models.expressions import When, Case
case = Case(
When(code='0001', then=10),
When(code='0002', then=15),
default=0, output_field=CharField(),
)
when_list = [When(code=line[0], then=line[1]) for line in lines]
case = Case(*when_list, default=0, output_field=CharField())
Product.objects.update(price=case)
ѧ 5. Django 1.8