How I can create fields into a model in dependence of another one?

I'm learning Django and I'm working in a test project.

So in my models.py I have this (I know that is wrong but I don't know how to do that):

from django.db import models

class Diagram(models.Model):
    name = models.CharField(max_length=100)
    img = models.ImageField(upload_to='img/diagrams/', help_text="Size required: height = 1050px, width = 1506px.", max_length=None)    
    
    def __str__(self):
        return self.name

class DiagramReferences(Diagram):
    quantity_of_references = models.IntegerField()

    for i in range(quantity_of_references):
        title = models.CharField(max_length=50)
        coords = models.CharField(max_length=50)

So I want to make a relation between both models, the first: Diagram contains the name of the Diagram and the respective image. In the other I want to select the first which was already created and assign him how many references it has and create a field for each reference.

First you are going to create Diagram. you should create a function for your upload directory:

def user_directory_path_img(instance, filename):
    # file will be uploaded to MEDIA_ROOT / user_<id>/<filename> if you've declared MEDIA path
    return 'img/diagrams/{0}/{1}-{2}'.format(instance.name, datetime.now(tz=pytz.UTC).date(), filename)

class Diagram(models.Model):
    name = models.CharField(max_length=100)
    img = models.ImageField((upload_to=user_directory_path_img, null=True, blank=True)   
    
    def __str__(self):
        return self.name

Then you are going to make a ForeignKey field . As vinkomlacic said you can not create dynamic relations and its advised not to mess with that. If you want to have different fields either make a TextField with multiple entries or arrays or just create the maximum number of fields that you think are required and set them to blank=True, null=True.

class DiagramReferences(models.Model):
   diagram = models.ForeignKey(Diagram, on_delete=models.CASCADE, blank=True, null=True, default=None)
   title = models.CharField(max_length=50, blank=True, null=True)
   coords = models.CharField(max_length=50, blank=True, null=True)
   extra = models.CharField(max_length=50, blank=True, null=True)
Back to Top