简体   繁体   English

在 Django 中创建一个 model ,其字段中包含多个其他字段

[英]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您还可以创建两个模型ScansResults并在它们之间创建如下关系

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.

相关问题 制作一个 Django model class 其字段值之一由其他模型的字段值计算,并且它必须存在于我的实际数据库表中 - Make a Django model class whose one of the field value is calculated by other model's fields values and it must be present in my actual Database table 更新模型字段和Django中的任何其他字段 - Update model field and any other fields in django 从其他字段计算的 Django 模型字段 - Django Model field calculated from other fields Django-模型字段为其他字段的总和 - Django - Model field to be the sum of other fields Django,在同一个 model 中创建多个相同的字段 - Django, creating multiple identical fields in the same model Django模型字段限制从其他模型字段中选择 - django model field limit choice from other model fields 如何将数据添加到其列被 Django 中的其他模型引用(外域)的模型中 - How to add data to the model whose column are referenced(Foreign Field) from other model in Django 如何使用 model 中的其他字段初始化 Django 模型中的字段 - How to initialise a field in Django models using other fields in the model Django模型:从模型实例中的其他字段生成字段内容 - Django Models: Generate field content from other fields in model instance 如何使用其他字段的值在 Django 模型中创建一个字段? - How to create a field in django model using values of other fields?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM