'Advise on orm modelling in django
I am building a webapp in which users place orders with nested information. I am after some advice on best practice so I can do some more research.
The idea is that a user either loads an existing order, or creates a new order. They then fill in the subsequent order fields, which can be on a one to many basis. My initial thought was to use a variable for order_id and use a foreign key to link the instances of the other classes. However, this seems overcomplicated. order_id would have to be unique and sequential. Is this the best approach to this issue?
class Order(models.Model):
order_id= xxxx
created_by = xxxx
class A(models.Model):
order_id = models.ForeignKey(xxxxx)
someclassafield = xxxx
class B(models.Model):
order_id = models.ForeignKey(xxxxx)
someclassbfield = xxxx
This would give the user the ability to create orders such as below:
Order 1
(Class_A, order_id, someclassafield)
(Class_A, order_id, someclassafield)
(Class_A, order_id, someclassafield)
(Class_B, order_id, someclassbfield)
Order 2
(Class_A, order_id, someclassafield)
(Class_A, order_id, someclassafield)
(Class_B, order_id, someclassbfield)
(Class_B, order_id, someclassbfield)
Solution 1:[1]
Answering my own question in case this is of any use to others. From research what I actually want is a one to many relationship. Source:
https://docs.djangoproject.com/en/4.0/topics/db/examples/many_to_one/
from django.db import models
class Reporter(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
email = models.EmailField()
def __str__(self):
return "%s %s" % (self.first_name, self.last_name)
class Article(models.Model):
headline = models.CharField(max_length=100)
pub_date = models.DateField()
reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE)
def __str__(self):
return self.headline
class Meta:
ordering = ['headline']
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Jonathan E |