zoro
zoro

Reputation: 109

Combine 2 models table data into 1 model (table),Django

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

Upvotes: 0

Views: 117

Answers (2)

Daniil Fajnberg
Daniil Fajnberg

Reputation: 18588

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

class Combined(NewJsonData, NewApiJsonData):
  pass

Upvotes: 1

ilyasbbu
ilyasbbu

Reputation: 1749

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

Upvotes: 1

Related Questions