Jaskaran singh Rajal
Jaskaran singh Rajal

Reputation: 2330

django ForeignKey relation how to get data other tables

I have 3 models

class product(models.Model):
  name = models.CharField(max_length=30)

class order(models.Model):
  order_number = models.CharField(max_length=30)

class order_products(models.Model):
  order_id = models.ForeignKey(order )
  product_id = models.ForeignKey(product )

One order has multiple products

is this relation is correct and if it is correct then if i get all the order then how can i get it related product data?

Upvotes: 0

Views: 501

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476659

This is a many-to-many relation. You can also specify this without an intermediate model with a ManyToManyField, or specify one on top of this model:

class Product(models.Model):
    name = models.CharField(max_length=30)

class Order(models.Model):
    order_number = models.CharField(max_length=30)
    products = models.ManyToManyField(
        Product,
        through='OrderProduct',
        related_name='orders'
    )

class OrderProduct(models.Model):
  order = models.ForeignKey(Order, on_delete=models.CASCADE)
  product = models.ForeignKey(Product, on_delete=models.CASCADE)

Here the ManyToManyField will thus consult the OrderProduct model to obtain the related Products (or Orders for a given Product). You can then access these more conveniently with:

myorder.products.all()

Where myorder is a Order object.

Some remarks:

  1. it is not clear why you used null=True. This would result in OrderProducts that no longer point to an Order or Product;
  2. Models are normally written in PerlCase, not snake_case, so OrderProduct, not order_product;
  3. Normally a ForeignKey has no _id suffix in its name, since Django will automatically add an _id suffix to field to generate a database field;
  4. you can later add a quantity field in the OrderProduct model to specify how many times the product has been ordered in a single Order, this makes the data more compact.

Upvotes: 1

Related Questions