Reputation: 2330
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
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 Product
s (or Order
s for a given Product
). You can then access these more conveniently with:
myorder.products.all()
Where myorder
is a Order
object.
Some remarks:
null=True
. This would result in OrderProduct
s that no longer point to an Order
or Product
;OrderProduct
, not order_product
;ForeignKey
has no _id
suffix in its name, since Django will automatically add an _id
suffix to field to generate a database field;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