简体   繁体   中英

Is there a way to select specific fields from model in django?

Is there a way to select some specific fields from model with Foreign Key. Here is an example: let's say I have

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

The purpose is to get the product name and product price in the Order class. Is there any way to do so? (I'm very new to Django and could find exactly this in the doc)

Thanks

Yes, you can query for example with:

from django.db.models import F

orders = Order.objects.annotate(
    product_name=F('product__name'),
    product_price=F('product_price')
)

The Order objects that arise from this queryset, will have two extra attribute .product_name and .product_price that contains the name and the price of te related Product .

In the Order object itself, you can just use self.product.name . You already do that, for example in the __str__ method. You can for example fetch the name and price of the related product with:

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., self)
        else:
            return 'no_product'

I found somehow something similar in here

Django ForeignKey limit_choices_to a different ForeignKey id

I'll implement this solution and see if it works for me

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM