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
Related
The problem is that with this approach, annotate ignores equal amounts, and if you remove distinct=True, then there will be duplicate objects and the difference will not be correct.
In simple words, I want to get the balance of the account by getting the difference between the amount in cash and the amount on receipts for this personal account
queryset = PersonalAccount.objects.select_related(
'apartment', 'apartment__house', 'apartment__section', 'apartment__owner',
).annotate(
balance=
Greatest(Sum('cash_account__sum', filter=Q(cash_account__status=True), distinct=True), Decimal(0))
-
Greatest(Sum('receipt_account__sum', filter=Q(receipt_account__status=True), distinct=True), Decimal(0))
).order_by('-id')
class PersonalAccount(models.Model):
objects = None
class AccountStatus(models.TextChoices):
ACTIVE = 'active', _("Активен")
INACTIVE = 'inactive', _("Неактивен")
number = models.CharField(max_length=11, unique=True)
status = models.CharField(max_length=8, choices=AccountStatus.choices, default=AccountStatus.ACTIVE)
apartment = models.OneToOneField('Apartment', null=True, blank=True, on_delete=models.SET_NULL,
related_name='account_apartment')
class CashBox(models.Model):
objects = None
number = models.CharField(max_length=64, unique=True)
date = models.DateField(default=datetime.date.today)
status = models.BooleanField(default=True)
type = models.BooleanField(default=True)
sum = models.DecimalField(max_digits=10, decimal_places=2)
comment = models.TextField(blank=True)
payment_items = models.ForeignKey('PaymentItems', blank=True, null=True, on_delete=models.SET_NULL)
owner = models.ForeignKey(User, blank=True, null=True, on_delete=models.SET_NULL, related_name='owner')
manager = models.ForeignKey(User, null=True, on_delete=models.SET_NULL, related_name='manager')
personal_account = models.ForeignKey('PersonalAccount', blank=True, null=True,
on_delete=models.SET_NULL, related_name='cash_account')
receipt = models.ForeignKey('Receipt', blank=True, null=True, on_delete=models.SET_NULL)
class Receipt(models.Model):
objects = None
class PayStatus(models.TextChoices):
PAID = 'paid', _("Оплачена")
PARTIALLY_PAID = 'partially_paid', _("Частично оплачена")
NOT_PAID = 'not_paid', _("Не оплачена")
number = models.CharField(max_length=64, unique=True)
date = models.DateField(default=datetime.date.today)
date_start = models.DateField(default=datetime.date.today)
date_end = models.DateField(default=datetime.date.today)
status = models.BooleanField(default=True)
status_pay = models.CharField(max_length=15, choices=PayStatus.choices, default=PayStatus.NOT_PAID)
sum = models.DecimalField(max_digits=10, decimal_places=2, default=0.00, blank=True)
personal_account = models.ForeignKey('PersonalAccount', blank=True, null=True,
on_delete=models.CASCADE, related_name='receipt_account')
tariff = models.ForeignKey('Tariff', null=True, on_delete=models.CASCADE)
apartment = models.ForeignKey('Apartment', null=True, on_delete=models.CASCADE,
related_name='receipt_apartment')
_Hi, guys! I'm trying to sum times for users for each Month(Mission), like this:
times = goal.time_set.filter(day__year=today.year, day__month=today.month)
Then I will sum:
for time in times:
total_min[member_number] = total_min[member_number] + time.value
But it calculates for current Month(Mission).
I want to calculate time depends on object model Mission. Model Mission:
class Mission(models.Model):
name = models.CharField(max_length=200, default='')
description = models.TextField(default='')
add_info = models.TextField(default='', blank=True)
theme = models.ImageField(upload_to='themes/', default='themes/default.png')
date_created = models.DateTimeField(null=True)
date_finished = models.DateTimeField(null=True, blank=True)
Like this I think:
times = goal.time_set.filter(day__year=mission.date_created.year, day__month=mission.month_created.month)
How can I achieve it?
upd. Goal model:
class Goal(models.Model):
STATUS = (
('in progress', 'in progress'),
('completed', 'completed'),
('failed', 'failed')
)
id_ninja = models.ForeignKey(Ninja, null=True, on_delete=models.SET_NULL)
id_user = models.ForeignKey(User, null=True, on_delete=models.SET_NULL)
name = models.CharField(max_length=150, default='')
description = models.TextField(default='')
date_created = models.DateTimeField(null=True)
status = models.CharField(max_length=20, choices=STATUS, default='in progress')
I solved the problem in my way.
mission_year = mission.date_created.strftime('%Y')
mission_month = mission.date_created.strftime('%m')
times = goal.time_set.filter(day__year__gte=mission_year, day__month__gte=mission_month)
I have the code which calculates the sum just fine, now my question is it possible to multiple each price by quantity and then get the total sum after that in a cart on my website. I have tried with all of my logic but i have failed. The idea is to get the price of an item added to cart and multiply it by quantity and then get the total.
Here is my cart mode. models.py:
#cart model
class Cart(models.Model):
item = models.ForeignKey(Item, on_delete=models.CASCADE)
number_of_items = models.IntegerField(default=0)
user = models.ForeignKey(User, on_delete=models.CASCADE)
added_datetime = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.item.name
#Item model
class Item(models.Model):
CONDITION = (
('new', 'new'),
('used', 'used'),
('not applicable', 'not applicable'),
)
name = models.CharField(max_length=250)
owner = models.CharField(max_length=250, default='Ludocs-emark')
category = models.ForeignKey(ItemCategories, on_delete=models.CASCADE)
sub_category = models.ForeignKey(SubCategory, on_delete=models.CASCADE)
tag = models.ForeignKey(Tag, on_delete=models.CASCADE)
Condition = models.CharField(max_length=250, null=True, choices=CONDITION)
price= models.IntegerField(default=0)
number_of_items = models.IntegerField(blank=True)
specification_one = models.CharField(max_length=250, blank=True)
specification_two = models.CharField(max_length=250, blank=True)
specification_three = models.CharField(max_length=250, blank=True)
specification_four = models.CharField(max_length=250, blank=True)
specification_five = models.CharField(max_length=250, blank=True)
specification_six = models.CharField(max_length=250, blank=True)
available_colors = models.CharField(max_length=250, blank=True)
description = RichTextField()
thumbnail = models.ImageField(default='default.png', upload_to='images/')
image_one = models.ImageField(upload_to='images/')
image_two = models.ImageField(upload_to='images/')
image_three = models.ImageField(upload_to='images/')
image_four = models.ImageField(upload_to='images/')
added_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.name
views.py file that i used to calculate the sum:
#This is the file where that i want to use to get the items added in cart and then multiply each by it's quantity and then get the total of the calculations when multiplied.
cart_sum = Cart.objects.filter(user=request.user).aggregate(Sum('item__price')).get('item__price__sum')
Yes, You can do that.
Try this
cart_sum = Cart.objects.filter(user=request.user).aggregate(Sum('item__price', field='item__price * number_of_items')).get('item__price__sum')
Assuming number_of_items as the quantity for the item from the Cart model.
Also you can return a total value so that if this gives any error for two different fields then you can do this
cart_sum = Cart.objects.filter(user=request.user).aggregate(total_price=Sum('item__price', field='item__price * number_of_items')).get('total_price')
I need to access columns in particular table through foreign keys in another table. I wrote it in SQL, but how it will be in queryset language?
This is models.py
class carModel(models.Model):
id_car_model = models.IntegerField(primary_key=True)
id_car_mark = models.ForeignKey(carMark,on_delete=models.CASCADE)
name = models.CharField(max_length=255)
date_create = models.IntegerField(max_length=10,null=True)
date_update = models.IntegerField(max_length=10,null=True)
id_car_type = models.ForeignKey(carType,on_delete=models.CASCADE)
name_rus = models.CharField(max_length=255,null=True)
class CarParts(models.Model):
id_catalog = models.IntegerField(primary_key=True)
manufacturer = models.CharField(max_length=200,blank=True, null=True)
vendor_code = models.IntegerField(blank=True, null=True)
subgroup = models.CharField(max_length=200,blank=True, null=True)
title = models.CharField(max_length=200,blank=True, null=True)
side = models.CharField(max_length=200,blank=True, null=True)
description = models.CharField(max_length=200,blank=True, null=True)
model = models.CharField(max_length=200,blank=True, null=True)
trade_mark = models.CharField(max_length=200,blank=True, null=True)
original_number = models.CharField(max_length=200,blank=True, null=True)
request = models.CharField(max_length=200,blank=True, null=True)
price = models.IntegerField(blank=True, null=True)
sum = models.IntegerField(blank=True, null=True)
availability = models.CharField(max_length=200,blank=True, null=True)
class interimTable(models.Model):
id_interim = models.IntegerField(primary_key=True)
description = models.CharField(max_length=100,null=True)
id_catalog=models.ForeignKey(CarParts, on_delete=models.CASCADE)
id_car_model = models.ForeignKey(carModel,on_delete=models.CASCADE)
This is SQL request, that is successful. I need same thing, but like querySet, to use it in further code.
Select title,side,price
from carinfo_carparts,carinfo_interimtable,carinfo_carmodel
where id_catalog = carinfo_interimtable.id_catalog_id
and carinfo_carmodel.id_car_model = carinfo_interimtable.id_car_model_id
and carinfo_carmodel.name='Civic';
this is the result
Try this,
CarParts.objects.filter(interimtable__id_car_model__name='Civic').values('title', 'side', 'price')
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?