Django collection of instances of same model

Viewed 93

I'm new to Django I'm currently using django 3.2.6. I want make multiple instances of route_stop model and store in SchoolRouteStop.route_graph model.I don't want use ForeignKey because i want to make somthing like like nested dict.

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.
1 Answers

You have to use a ForeignKey here because you will lose all the Django ORM features and performances if you try to hack this.
Trying to use a JSONField or something else instead would also mean losing integrity constraints you would need to implement yourself, which you really want to avoid.

The way Django works is you implement your models to be stored efficiently in the database, then you use views & serializers to manipulate them.

Your models need to be refined, I really have a hard time understanding their real purpose because there are id fields everywhere (that should also probably be ForeignkeyField), and everything seems a little confusing.
For example, why is school_route_stop_uuid a CharField when UUIDField does exist?
Why is route_id not a property?

Also, make sure to follow the naming conventions in Python, it will make you code way cleaner. According to PEP 8 (https://www.python.org/dev/peps/pep-0008/#class-names):

Class names should normally use the CapWords convention.

Related