1

Having a lot of models, I have started to factor out common blocks with the aim of my database reaching second normal form. As the application should be used by a sales team, most entries are some kind of orders. An excerpt from my models file looks like this:

class Order(models.Model):
    dl = models.CharField(max_length=100)
    cl = models.CharField(max_length=100)
    (...)

class Setup(models.Model):
    order = models.ForeignKey(Order) # could be OneToOneField()
    name = models.CharField(max_length=200)
    package = models.CharField(choices=(
        ('S', 'Small'),
        ('M', 'Medium'),
        ('L', 'Large'),
        ('XL', 'Extra large'),
        ('C', 'Custom')
    ), max_length=2)
    server = models.ForeignKey(Webserver)
    (...)

While it does not make any logical sense to keep the order details out of the model for a setup order, it helps to keep the project maintainable, since setup orders are not the only things coming in and this way you can change the order model and all other models/orders are updated too.

Here comes the problem. For attributes like Setup.server Django's default behaviour of creating a dropdown with all web servers the company can offer is totally fine. If the team decides to add another one, it can simply create another server option on another page. But for order, I would like that the OrderForm is included on the same page as the SetupForm, ideally as a separate Fieldset. After submitting the form, the new order should be added to the database and Setup.order is to be filled. I know that I can code it for this special case, but the application will contain numerous forms, so a generic solution would be better.

A possible solution could be to create a custom models.ForeignKey or models.OneToOneField with a custom option and a generic view that than renders a template with two forms and links the objects afterwards.

Did anyone have a similar problem? Does anyone know a simple, maybe even builtin solution to that?

EDIT 1

I have thought about inline formsets which were the solution to a similar question which used this example

class Contact(models.Model):

    ...

class Communication(models.Model):

   contact = models.ForeignKey(Contact)

and by using a communication fieldset. However, this treats the class containing as the child, which is not the case in my example. But it still is an option, even if it would still have to be automated so it can be used quickly for all links between the other models.

Nick Lehmann
  • 598
  • 1
  • 7
  • 25

0 Answers0