【问题标题】:Django collection of instances of same model相同模型实例的 Django 集合
【发布时间】:2021-08-15 18:59:09
【问题描述】:

我是 Django 新手 我目前正在使用 django 3.2.6。我想制作 route_stop 模型的多个实例并存储在 SchoolRouteStop.route_graph 模型中。我不想使用 ForeignKey 因为我想制作类似嵌套字典之类的东西。

from django.db import models


class geo_fence(models.Model):
    radius = models.FloatField()

class geo_location(models.Model):
    latitude = models.FloatField()
    longitude = models.FloatField()

class address(models.Model):
    entity = models.fields.CharField(max_length=100)
    apt_plot = models.fields.CharField(max_length=100)
    street = models.fields.CharField(max_length=100)
    city = models.fields.CharField(max_length=100)
    state = models.fields.CharField(max_length=2) #state name in short code
    zip_code = models.fields.IntegerField()

class route_stop(models.Model): # this for multiple bus stops
    route_stop_id =  models.fields.IntegerField()
    school_id = models.fields.CharField(max_length=100)
    route_number = models.fields.CharField(max_length=100)
    school_route_stop_uuid = models.fields.CharField(max_length=100, primary_key=True)
    registered_arrival_time = models.TimeField()
    time_from_src = models.FloatField()
    is_school = models.BooleanField(default=False)
    geo_fence = models.ForeignKey(geo_fence, on_delete =models.CASCADE)
    geo_location = models.ForeignKey(geo_location, on_delete = models.CASCADE)
    address = models.ForeignKey(address, on_delete = models.CASCADE)


class SchoolRouteStop(models.Model):
    school_id = models.CharField(max_length=100)
    school_route_number = models.IntegerField()
    route_type = models.CharField(max_length=2)
    route_id = str(school_id)+'_'+str(school_route_number)+str(route_type)
    route_graph= models.ForeignKey(route_stop,related_name='School', on_delete = models.CASCADE)
    



# Create your models here.

【问题讨论】:

    标签: python django django-models django-rest-framework


    【解决方案1】:

    您必须在此处使用 ForeignKey,因为如果您尝试破解它,您将失去所有 Django ORM 功能和性能。
    尝试使用 JSONField 或其他东西也意味着失去您需要自己实现的完整性约束,这是您真正想要避免的。

    Django 的工作方式是您将模型高效地存储在数据库中,然后使用视图和序列化器来操作它们。

    您的模型需要改进,我真的很难理解它们的真正用途,因为到处都有 id 字段(也应该是 ForeignkeyField),而且一切看起来都有些混乱。
    例如,UUIDField does exist 时为什么 school_route_stop_uuid 是 CharField?
    为什么route_id 不是属性?

    另外,请确保遵循 Python 中的命名约定,这将使您的代码更加简洁。根据 PEP 8 (https://www.python.org/dev/peps/pep-0008/#class-names):

    类名通常应使用 CapWords 约定。

    【讨论】:

    • @54_ManishJain 如果您需要更多帮助,请随时添加类图,以便我们更好地了解您正在尝试做什么。
    猜你喜欢
    • 2018-06-12
    • 2018-04-24
    • 1970-01-01
    • 2018-03-21
    • 1970-01-01
    • 1970-01-01
    • 2022-09-27
    • 2011-01-31
    • 1970-01-01
    相关资源
    最近更新 更多