[英]Creating a model in Django whose field has multiple other fields inside it
I'm quite new to Django and would like to clear a noob doubt.我对 Django 很陌生,想澄清一个菜鸟疑问。 Say I have a post request to a model
Scans
in django.假设我对 django 中的 model
Scans
有一个发布请求。
The json data for the same looks like同样的 json 数据看起来像
[{"id":1, "results":{"low": 3, "medium": 6, "high": 7}, "machine": "Windows", "report": "yes"]
[{“id”:1,“结果”:{“低”:3,“中”:6,“高”:7},“机器”:“Windows”,“报告”:“是”]
How should the model look like? model 应该是什么样子? I can't figure out what field type I should give to
results
.我不知道应该给
results
什么字段类型。
Try out JSONField .试试JSONField 。 Your model should look like that.
你的 model 应该是这样的。
from django.contrib.postgres.fields import JSONField
from django.db import models
class Scans(models.Model):
machine = models.CharField(...)
results = JSONField(default=dict)
PS You need to configure your database(in this case PostgreSQL) PS你需要配置你的数据库(在这种情况下是PostgreSQL)
PSS If you dont want to use PostgreSQL here is JSONFIeld for MySQL PSS 如果你不想使用 PostgreSQL 这里是 MySQL 的JSONFIeld
You can also create two models Scans
and Results
and create a relationship between them as follows您还可以创建两个模型
Scans
和Results
并在它们之间创建如下关系
class Scans(models.Model):
machine = models.CharField(max_length = 100)
# assuming that report is by default false
report = models.BooleanField(default = False)
results = models.ForeignKey(Results, on_delete = models.CASCADE)
class Results(models.Model):
low = models.IntegerField()
medium = models.IntegerField()
high = models.IntegerField()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.