Home > Software engineering >  Combine 2 models table data into 1 model (table),Django
Combine 2 models table data into 1 model (table),Django

Time:08-24

models.py:

class NewJsonData(models.Model):
    speed = models.IntegerField()
    heading = models.IntegerField()
    altitude = models.FloatField()
    accuracy = models.FloatField()
    longitude = models.FloatField()
    altitudeAccuracy = models.FloatField(null=True)
    latitude = models.FloatField()
    
    pass

class NewApiJsonData(models.Model):
    _id = models.CharField(null=True, max_length=100)
    coords = models.ForeignKey(
        NewJsonData, on_delete=models.CASCADE, null=True, blank=True)
    mocked = models.BooleanField()
    timestamp = models.FloatField()
    _v = models.IntegerField(null=True)
    createdAt = models.CharField(null=True, max_length=100)
    updatedAt = models.CharField(null=True, max_length=100)

I was trying to create a new table having contents of both models as seen in below picture.enter image description here

Table of NewJsonData looks as: enter image description here

and table of NewApiJsonData looks as:

enter image description here

CodePudding user response:

These are classes. Use multiple inheritance, if you know there will be no conflicts:

class Combined(NewJsonData, NewApiJsonData):
  pass

CodePudding user response:

You can inherit one model to another in django

class NewJsonData(models.Model):
    speed = models.IntegerField()
    heading = models.IntegerField()
    altitude = models.FloatField()
    accuracy = models.FloatField()
    longitude = models.FloatField()
    altitudeAccuracy = models.FloatField(null=True)
    latitude = models.FloatField()

class NewApiJsonData(NewJsonData): #inherit above model
    _id = models.CharField(null=True, max_length=100)
    coords = models.ForeignKey(
        NewJsonData, on_delete=models.CASCADE, null=True, blank=True)
    mocked = models.BooleanField()
    timestamp = models.FloatField()
    _v = models.IntegerField(null=True)
    createdAt = models.CharField(null=True, max_length=100)
    updatedAt = models.CharField(null=True, max_length=100)

so the resulting NewApiJsonData contains the fields of NewJsonData

  • Related