1

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

  • Does this answer your question? [Django accessing ForeignKey model objects](https://stackoverflow.com/questions/9622047/django-accessing-foreignkey-model-objects) – MrProgrammer Apr 08 '20 at 19:49
  • @UtkarshGupta not really, maybe I'm not asking the question the right way. – Salim Houari Apr 08 '20 at 20:14

2 Answers2

1

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.product.name, self.product.price)
        else:
            return 'no_product'
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
  • Thanks for the explanation, but for some reason it is not working it is giving me this error return '{}: {}'.format(self.product.name, self.product.price) ^ TabError: inconsistent use of tabs and spaces in indentation. With this solution, does product_name and price become attributes of Order? actually this is what I want. – Salim Houari Apr 09 '20 at 05:38
0

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