[Answered ]-Django Model conditional relationship

1👍

Actually you only need one model. All geometry fields are derived from GeometryField so you can use it to store it’s sub classes.

PRJ_GEOM = (
         (1, "point"),
         (2, "line"),
         (3, "polygon")
  )

class Project(models.Model):
    name = models.CharField(max_length=20)
    project_geom_type = models.IntegerField(choices=PRJ_GEOM)
    project_geometry = models.GeometryField()

That is all! one model, one table instead of four which is much easier to maintain. And the data is slightly smaller because the relation field is eliminated.

👤e4c5

1👍

Your Project model doesn’t need the project_geometry fields. You only need to relate your different geometry models to the project using your OneToOne field. Django automatically creates reverse relationships for ForeignKey, ManyToMany and OneToOne relationships. Your classes would look something like this:

class Project(models.Model):
    name = models.CharField(max_length=20)

class Point_Geo(models.Model):
      project = models.OneToOne(Project) # truncated for example
      point = models.PointField()

class Line_Geo(models.Model):
      project = models.OneToOne(Project) # truncated for example
      line = models.LineStringField()

class Polygon_Geo(models.Model):
      project = models.OneToOne(Project) # truncated for example
      polygon = models.PolygonField()

When you’ve got a Project instance you can walk back along the reverse relationship like this:

project = Project.objects.get(id=1)
point = project.point_geo.point

To query for all projects with point geometry you could query:

projects_with_points = Project.objects.exclude(point_geo=None)
👤Soviut

Leave a comment