簡體   English   中英

有沒有辦法從 django 中的 model 中的 select 特定字段?

[英]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 ,其中包含相關Productnameprice

Order object 本身中,您可以只使用self.product.name 您已經這樣做了,例如在__str__方法中。 例如,您可以通過以下方式獲取相關productnameprice

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'

我在這里發現了類似的東西

Django ForeignKey limit_choices_to a different ForeignKey id

我將實施這個解決方案,看看它是否適合我

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM