Search code examples
pythondjangopostgresqldjango-modelspython-dataclasses

Using Python Dataclass in Django Models


My goal is to create a struct-like object in Django PostgreSQL, such as:

specs.coordinate.x
specs.coordinate.y
specs.coordinate.z

x,y,z should therefore be subclasses of coordinate. They should be me mutable as well, wherefore named tuples cannot be used.

I have tried it using the new dataclass:

from django.db import models
from dataclasses import dataclass

class Specs(models.Model):
    name = models.CharField(max_length=80)
    age = models.IntegerField()

    @dataclass
    class coordinate:
        x: float
        y: float
        z: float

However the coordinate x,y,z items are not visible in pgAdmin:

enter image description here

What am I doing wrong? Is there any better approach for this than with dataclass?


Solution

  • If your goal is simply to use the syntax: specs.coordinate.x in your datasheet you can simply use a OneToOne Relation.

    This also allows for the special case, that either all Coordinates values have to be set or none.

    from django.db import models
    
    class Coordinate(models.Model):
        x = models.FloatField()
        y = models.FloatField()
        z = models.FloatField()
    
    
    class Specs(models.Model):
        name = models.CharField(max_length=80)
        age = models.IntegerField()
        coordinate = models.OneToOneField(
            Coordinate, 
            null=True, 
            on_delete=models.SET_NULL
        )
    
    

    Now you can use Specs just like the a Dataclass.