【问题标题】:How to design a model and its child django如何设计模型及其子 django
【发布时间】:2020-08-21 08:58:32
【问题描述】:

如何在 django 中设计一个模型以将以下 JSON 值存储在单个模型中

class Bus(models.Model):
    source = models.CharField(max_length=200)
    destination = models.CharField(max_length=200)
    type= models.CharField(max_length=200)
    price=models.FloatField()

我需要接受下面的 json 才能接受并存储在同一张表中 如果我可以使用 ListField ,那么它将如何用于连接

  {  
     "source": "delhi",
     "destination": "pune",
     "type": "Economy",
     "price":300.0,
     "Connections": [
                        {
                            "source": "lon",
                            "destination": "liverpool",
                            "type": "luxury",
                         },
                        {
                            "source": "banglur",
                            "destination": "cochin",
                            "type": "luxury",
                         }
                    ],
}

【问题讨论】:

    标签: django serialization django-rest-framework model


    【解决方案1】:

    您可以使用Foreign Keys。

    from django.db import models
    
    class Connection:
        source = models.CharField(max_length=256)
        destination = models.CharField(max_length=256)
        type = models.CharField(max_length=256)
    
    class Bus(models.Model):
        source = models.CharField(max_length=256)
        destination = models.CharField(max_length=256)
        type = models.CharField(max_length=256)
        price = models.FloatField()
        connections = models.ForeignKey(Connection, on_delete=models.CASCADE)
    

    或JsonField。

    from django.contrib.postgres.fields import JSONField
    from django.db import models
    
    class Bus(models.Model):
            source = models.CharField(max_length=256)
            destination = models.CharField(max_length=256)
            type = models.CharField(max_length=256)
            price = models.FloatField()
            connections = JSONField()
    

    【讨论】:

    • 这不是解决方案,我需要一个模型中的所有内容
    • 我知道我可以通过设计另一个模型并建立外键关系来解决这个问题,这就是为什么我重复我的问题两次(单个模型中的 JSON 值,存储在同一个表中)
    • 更新了我的答案。
    • DictField 是 Django Rest Framework 序列化程序的一部分,而不是 Django。
    • 不客气,如果对你有帮助,请接受我的回答:)
    猜你喜欢
    • 2013-05-13
    • 2018-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    相关资源
    最近更新 更多