I am building a system to register parts for manufacturing (for context: temperature sensors).
As I'm dealing with many different subtypes of actual physical parts, I'm using django-polymorphic to define the models for the actual temperature sensors:
class TempSensor(PolymorphicModel):
"""Abstract model for temperature sensors""""
part_number = models.OneToOneField(Part, on_delete=models.CASCADE)
class TempSensorA1(TempSensor):
calibration = models.CharField(max_length=1, choices=Calibration.choices)
junction = models.CharField(max_length=1, choices=Junction.choices)
def __str__(self):
return f"A1-{self.calibration}{self.junction}"
class TempSensorB1(TempSensor):
calibration = models.CharField(max_length=1, choices=Calibration.choices)
termination = models.CharField(max_length=1, choices=Termination.choices)
def __str__(self):
return f"B1-{self.calibration}{self.termination}"
The Part model acts as a container for the TempSensor instances. This lets me assign a simpler consecutive part number and associate them with orders.
class Part(models.Model):
part_number = models.AutoField(primary_key=True)
order = models.ManyToManyField(Order, through="OrderDetail")
production_notes = models.TextField(blank=True)
sales_notes = models.TextField(blank=True)
class Meta:
ordering = ["part_number"]
Right now, I have the django admin interface working as expected. When adding a new Part instance, I can add a TempSensor, select the correct child type and input the fields manually, all through an inline. This works great when working from raw specifications.
However, since model codes are often provided directly, I also need to be able to instantiate TempSensor directly from the model code.
To solve this, I've created a create_from_model_code method that takes the model code, parses it to identify the correct TempSensor subtype, and instantiates the model accordingly. This works well, but I can't figure out how to integrate both methods into admin simultaneously.
Ideally, I would have "Create temperature sensor" and "Create from model code" buttons that would load the correct form. Alternatively, I've thought of using create_from_model_code to get the desired values and fill out the form, but I'm not sure how to do that.
What is the best way to have two different methods of instantiating a model?
You can use generic relationship to solve your problem