[英]Is there a way to select specific fields from model in django?
有沒有辦法使用外鍵從 model 中獲取 select 的某些特定字段。 這是一個例子:假設我有
class Product(models.Model):
CATEGORY = (
('A', 'A'),
('B', 'B'),
('C', 'C'),
)
name = models.CharField(max_length=200, null=True)
price = models.FloatField(null=True)
category = models.CharField(max_length=200, null=True, choices=CATEGORY)
description = models.CharField(max_length=200, null=True)
date_created = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.name
class Order(models.Model):
STATUS = (
('Work Under Progress', 'Work Under Progress'),
('Delivered', 'Delivered'),
)
product = models.ForeignKey(Product, null=True, on_delete=models.SET_NULL)
date_created = models.DateTimeField(auto_now_add=True)
status = models.CharField(max_length=200, null=True,
choices=STATUS)
def __str__(self):
return self.product.name
目的是獲取訂單 class 中的產品名稱和產品價格。 有什么辦法嗎? (我對 Django 很陌生,可以在文檔中找到這個)
謝謝
是的,您可以查詢例如:
from django.db.models import F
orders = Order.objects.annotate(
product_name=F('product__name'),
product_price=F('product_price')
)
從此查詢集中產生的Order
對象將有兩個額外的屬性.product_name
和.product_price
,其中包含相關Product
的name
和price
。
在Order
object 本身中,您可以只使用self.product.name
。 您已經這樣做了,例如在__str__
方法中。 例如,您可以通過以下方式獲取相關product
的name
和price
:
class Order(models.Model):
STATUS = (
('Work Under Progress', 'Work Under Progress'),
('Delivered', 'Delivered'),
)
product = models.ForeignKey(Product, null=True, on_delete=models.SET_NULL)
date_created = models.DateTimeField(auto_now_add=True)
status = models.CharField(max_length=200, null=True,
choices=STATUS)
def __str__(self):
if self.product_id is not None:
return '{}: {}'.format(self.product.name, self.product.price)
else:
return 'no_product'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.