Technology Sharing

F objects in Django ORM

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

F Objects are very powerful and can perform complexBetween fieldsOperation.

Suppose we have a model containing product information Product

from django.db import models

class Product(models.Model):
    name = models.CharField(max_length=100)
    price = models.DecimalField(max_digits=10, decimal_places=2)
    discount_price = models.DecimalField(max_digits=10, decimal_places=2)
    stock = models.IntegerField()

    def __str__(self):
        return self.name
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

1. Compare the values ​​of two fields

Get all items whose discounted price is lower than the original price:

from django.db.models import F

# 获取所有折扣价低于原价的商品
discounted_products = Product.objects.filter(discount_price__lt=F('price'))
for product in discounted_products:
    print(product.name, product.price, product.discount_price)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

2. Arithmetic operations between fields

Calculate the discount amount for each item (original price minus discounted price) and sort by discount amount:

# 计算每个商品的折扣金额,并按折扣金额排序
products_with_discount = Product.objects.annotate(
    discount_amount=F('price') - F('discount_price')
).order_by('-discount_amount')

for product in products_with_discount:
    print(product.name, product.price, product.discount_price, product.discount_amount)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

3. Use F Update the object

Increase the price of all items with less than 10 in stock by 10%:

# 将所有库存少于10的商品的价格提高10%
Product.objects.filter(stock__lt=10).update(price=F('price') * 1.10)
  • 1
  • 2

4. Combination F Objects and Aggregate Functions

Calculate the average discount amount for items with inventory greater than 20:

from django.db.models import Avg

# 计算库存大于20的商品的平均折扣金额
average_discount = Product.objects.filter(stock__gt=20).annotate(
    discount_amount=F('price') - F('discount_price')
).aggregate(Avg('discount_amount'))

print(average_discount)  # 输出: {'discount_amount__avg': 例如 15.00}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

5. Use F Conditional update of objects

Set the discount price for all items with less than 10 in stock to 90% of the original price:

# 将所有库存少于10的商品的折扣价设置为原价的90%
Product.objects.filter(stock__lt=10).update(discount_price=F('price') * 0.90)
  • 1
  • 2

6. Use F Compare and filter fields between objects

Get all products with a discount amount greater than 20:

# 获取所有折扣金额大于20的商品
products_with_large_discount = Product.objects.annotate(
    discount_amount=F('price') - F('discount_price')
).filter(discount_amount__gt=20)

for product in products_with_large_discount:
    print(product.name, product.price, product.discount_price, product.discount_amount)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7