在Django模型中使用Python数据类 [英] Using Python Dataclass in Django Models

查看:61
本文介绍了在Django模型中使用Python数据类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标是在Django PostgreSQL中创建类似结构的对象,例如:

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 应该是坐标的子类.它们也应该是可变的,因此不能使用命名的元组.

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

但是坐标x,y,z 在pgAdmin中不可见:

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

我做错了什么?有没有比使用数据类更好的方法?

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

推荐答案

如果您的目标只是使用语法:在数据表中的 specs.coordinate.x 中,您只需使用 OneToOne 关系即可.

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
    )

现在,您可以像使用数据类一样使用Specs.

Now you can use Specs just like the a Dataclass.

这篇关于在Django模型中使用Python数据类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆