I've written some Django models and loaded some data for a bus timetable system but am having trouble with writing a query. Here are the models:
class VehicleJourney(models.Model):
vehicle_journey = models.CharField(primary_key=True, max_length=100)
journey_pattern = models.ForeignKey('JourneyPattern')
departure_time = models.TimeField()
class TimingLink(models.Model):
timing_link = models.CharField(primary_key=True, max_length=100)
journey_pattern = models.ForeignKey('JourneyPattern')
from_seq_no = models.IntegerField()
from_stop = models.ForeignKey('Stop', related_name='+')
to_seq_no = models.IntegerField()
to_stop = models.ForeignKey('Stop', related_name='+')
runtime = models.IntegerField()
class Stop(models.Model):
stop_point = models.CharField(primary_key=True, max_length=100)
common_name = models.CharField(max_length=250)
class JourneyPattern(models.Model):
journey_pattern = models.CharField(primary_key=True, max_length=100)
direction = models.CharField(max_length=100)
service = models.ForeignKey('Service')
class Service(models.Model):
service_code = models.CharField(primary_key=True, max_length=100)
registered_operator_ref = models.ForeignKey('Operator')
mode = models.CharField(max_length=100)
description = models.CharField(max_length=250)
start_date = models.DateField()
end_date = models.DateField()
origin = models.CharField(max_length=250)
destination = models.CharField(max_length=250)
The query takes an input of from_stop, to_stop and an arrival time to find the 3 next buses departing from from_stop,and arriving at to_stop by arrival_time.
I want to return the TimingLinks between from_stop and to_stop, with each runtime successively added to VehicleJourney.departure_time giving departure times for each stop.
Any insights on how I could best approach this?
Related
models.py:
class NewJsonData(models.Model):
speed = models.IntegerField()
heading = models.IntegerField()
altitude = models.FloatField()
accuracy = models.FloatField()
longitude = models.FloatField()
altitudeAccuracy = models.FloatField(null=True)
latitude = models.FloatField()
pass
class NewApiJsonData(models.Model):
_id = models.CharField(null=True, max_length=100)
coords = models.ForeignKey(
NewJsonData, on_delete=models.CASCADE, null=True, blank=True)
mocked = models.BooleanField()
timestamp = models.FloatField()
_v = models.IntegerField(null=True)
createdAt = models.CharField(null=True, max_length=100)
updatedAt = models.CharField(null=True, max_length=100)
I was trying to create a new table having contents of both models as seen in below picture.
Table of NewJsonData looks as:
and table of NewApiJsonData looks as:
You can inherit one model to another in django
class NewJsonData(models.Model):
speed = models.IntegerField()
heading = models.IntegerField()
altitude = models.FloatField()
accuracy = models.FloatField()
longitude = models.FloatField()
altitudeAccuracy = models.FloatField(null=True)
latitude = models.FloatField()
class NewApiJsonData(NewJsonData): #inherit above model
_id = models.CharField(null=True, max_length=100)
coords = models.ForeignKey(
NewJsonData, on_delete=models.CASCADE, null=True, blank=True)
mocked = models.BooleanField()
timestamp = models.FloatField()
_v = models.IntegerField(null=True)
createdAt = models.CharField(null=True, max_length=100)
updatedAt = models.CharField(null=True, max_length=100)
so the resulting NewApiJsonData contains the fields of NewJsonData
These are classes. Use multiple inheritance, if you know there will be no conflicts:
class Combined(NewJsonData, NewApiJsonData):
pass
My model
class Ad_company(models.Model):
idx = models.AutoField(primary_key=True)
subject = models.CharField(max_length=255)
memo = models.CharField(max_length=255)
content = models.TextField()
is_display = models.CharField(max_length=1)
writer = models.CharField(max_length=255)
write_date = models.DateTimeField()
update_date = models.DateTimeField()
delete_date = models.DateTimeField()
deadline_date = models.DateTimeField()
reply = models.IntegerField(blank=True)
hits = models.IntegerField(blank=True)
ad_apply = models.IntegerField(blank=True)
ad_category1 = models.CharField(max_length=255)
ad_category2 = models.CharField(max_length=255)
ad_place = models.CharField(max_length=255)
ad_age = models.CharField(max_length=255)
ad_sex = models.CharField(max_length=255)
ad_budget = models.BigIntegerField()
ad_length = models.CharField(max_length=255)
is_done = models.CharField(max_length=1)
is_pay = models.CharField(max_length=1)
ad_service = models.CharField(max_length=255)
ad_object = models.CharField(max_length=255)
is_file = models.CharField(max_length=1)
ad_require = models.CharField(max_length=255)
class Meta:
managed = False
db_table = 'ad_write_company'
class Ad_company_apply(models.Model):
idx = models.AutoField(primary_key=True)
parent_idx = models.IntegerField()
username = models.CharField(max_length=255)
content = models.TextField()
date = models.DateTimeField(default=datetime.now, blank=True)
budget = models.BigIntegerField()
term = models.IntegerField()
is_done = models.CharField(max_length=1)
SELECT * FROM ad_write_company INNER JOIN ad_write_company_apply ON ad_write_company.idx = ad_write_company_apply.parent_idx where ad_write_company_apply.is_done = 1 and ad_write_company_apply.username = 'asdffdsa'
This is my query. but I can not make join query with orm.
Sorry for question is too short.
And Is my query right?
I not sure of that. Thanks for answer.
or do you guys have other good idea?
I would advise to work with a ForeignKey from Ad_company_apply to Ad_company. This makes it easier to generate queries in Django and will guarantee referential integrity.
It thus makes sense to rewrite the Ad_company_apply model to:
class Ad_company_apply(models.Model):
# …
parent_idx = models.ForeignKey(
Ad_company,
db_column='parent_idx',
on_delete=models.CASCADE
)
# …
In that case, you can .filter(…) [Django-doc] with:
Ad_Company.objects.filter(ad_company_appy__isdone=1, ad_company_appy__username='asdffdsa')
Note: Models in Django are written in PascalCase, not snake_case,
so you might want to rename the model from Ad_company to AdCompany.
i have multiple models like,
class Service1(models.Model):
price = models.FloatField()
description = models.TextField()
class Service2(models.Model):
price = models.FloatField()
monthly_binifit = models.CharField()
description = models.TextField()
class Service3(models.Model):
price = models.FloatField()
free_contact = models.IntegerField()
monthly_binifit = models.CharField()
class Service4(models.Model)
price = models.FloatField()
monthly_binifit = models.CharField()
description = models.TextField()
other_binifit = models.CharField()
class Orders(models.Model):
user = models.ForeignKey(User, on_delete=models.CASECAD)
orders = models.ForeignKey((Service1, Service2, Service3, Service4), on_delete=models.CASECAD)
how is this possible to create orders with different services like above
I don't fully understand what you're trying to do without all the details but why can't you just have 'Services' as a foreign key and have Service1, Service2, Service3, Service4 as objects in objects in Services?
class Services(models.Model)
service = (
('Service1', ('Service1')),
('Service2', ('Service2')),
('Service3', ('Service3')),
('Service4', ('Service4')),
)
name = models.CharField(choices=service)
class Orders(models.Model)
orders = models.ForeignKey(Services,)
The best option I come with is to set the foreign relationships in the opposite direction:
class Service1(models.Model):
price = models.FloatField()
description = models.TextField()
order = models.ForeignField(Order, on_delete=models.PROTECT, related_name='services1')
class Service2(models.Model):
price = models.FloatField()
monthly_binifit = models.CharField()
description = models.TextField()
order = models.ForeignField(Order, on_delete=models.PROTECT, related_name='services2')
class Service3(models.Model):
price = models.FloatField()
free_contact = models.IntegerField()
monthly_binifit = models.CharField()
order = models.ForeignField(Order, on_delete=models.PROTECT, related_name='services3')
class Service4(models.Model)
price = models.FloatField()
monthly_binifit = models.CharField()
description = models.TextField()
other_binifit = models.CharField()
order = models.ForeignField(Order, on_delete=models.PROTECT, related_name='services4')
class Orders(models.Model):
user = models.ForeignKey(User, on_delete=models.CASECAD)
This way you can query for the services related to an order, one type at a time:
order = Order.objects.get(id=1)
services_1 = order.services1.all()
services_2 = order.services2.all()
services_3 = order.services3.all()
services_4 = order.services4.all()
You can't. But you can filter the objects in your function to reach the a specific class object.
How do I calculate the total with the existing model fields
class Book(models.Model):
school_id = models.ForeignKey(School)
name = models.CharField(max_length=100, default=None, blank=None,
unique=True)
class_name = models.CharField(max_length=50)
category = models.ForeignKey(Category)
bundle = models.CharField(max_length=20, unique=True)
particulars = models.CharField(max_length=50)
tax_code = models.CharField(max_length=50, default=None)
amount = models.FloatField()
tax_CGST = models.FloatField(default=0)
tax_SGST = models.FloatField(default=0)
total = models.FloatField()
def total(self):
return ((self.tax_SGST+self.tax_CGST)*self.amount)/100
def __str__(self):
return self.name
In the above code, I want the total function to calculate the total from the Tax and amount fields and add it to the total field in the database
How can I get the foreign key values? I have a common vehicle model that links to the year, series, engine type, body style, transmission and drive train...all as foreign keys. I'd like to get the values of these fields for my app, but I'm stuck as to how I'd go about them. Any ideas will be highly appreciated.
class Model(models.Model):
model = models.CharField(max_length=15, blank=False)
manufacturer = models.ForeignKey(Manufacturer)
date_added = models.DateField()
def __unicode__(self):
name = ''+str(self.manufacturer)+" "+str(self.model)
return name
class Year(models.Model):
ALPHA_NUMERIC_CHOICES = (
('1', 'Numeric'),
('A', 'Alphabetic'),
)
year = models.PositiveSmallIntegerField()
position_7_char = models.CharField(max_length=1, choices=ALPHA_NUMERIC_CHOICES)
position_10 = models.CharField(max_length=1, blank=False)
def __unicode__(self):
return unicode(self.year)
class Series(models.Model):
series = models.CharField(max_length=20, blank=True)
model = models.ForeignKey(Model)
date_added = models.DateField()
def __unicode__(self):
name = str(self.model)+" "+str(self.series)
return name
class CommonVehicle(models.Model):
year = models.ForeignKey(Year)
series = models.ForeignKey(Series)
engine = models.ForeignKey(Engine)
body_style = models.ForeignKey(BodyStyle)
transmission = models.ForeignKey(Transmission)
drive_train = models.ForeignKey(DriveTrain)
def __unicode__(self):
name = ''+str(self.year)+" "+str(self.series)
return name
class Vehicle(models.Model):
stock_number = models.CharField(max_length=6, blank=False)
vin = models.CharField(max_length=17, blank=False)
common_vehicle = models.ForeignKey(CommonVehicle)
exterior_colour = models.ForeignKey(ExteriorColour)
interior_colour = models.ForeignKey(InteriorColour)
interior_type = models.ForeignKey(InteriorType)
odometer_unit = models.ForeignKey(OdometerUnit)
status = models.ForeignKey(Status)
odometer_reading = models.PositiveIntegerField()
selling_price = models.PositiveIntegerField()
purchase_date = models.DateField()
sales_description = models.CharField(max_length=60, blank=False)
def __unicode__(self):
return self.stock_numberodels.ForeignKey(CommonVehicle)
You need the actual IDs? Try something like my_vehicle_ref.series.id.
Also, I hope you know that the series attribute right there is really an instance of Series, so you could access any of it's properties, e.g., my_vehicle_ref.series.model.model.