I have this model:
#Model for match result forecast
class ResultForecast(models.Model):
user = models.ForeignKey(User)
created_date = models.DateTimeField('match date', blank=True, null=True)
home_goals = models.DecimalField(max_digits=5, decimal_places=0, blank=True, null=True)
away_goals = models.DecimalField(max_digits=5, decimal_places=0, blank=True, null=True)
match = models.ForeignKey(Match, related_name='forecasted_match')
So I wanna get the objects where de home_goals are greater than the away goals and vice versa, I use this:
total_forecast = ResultForecast.objects.filter(match=match).count()
home_trend = ResultForecast.objects.filter(match=match, home_goals__gt=F('away_goals'))
away_trend = ResultForecast.objects.filter(match=match, away_goals__gt=F('home_goals'))
But it does not work
I am wondering if match should actually be match__exact? Have you tried the following to see if it makes any difference? I also prefer to use the Q class. https://docs.djangoproject.com/en/1.7/ref/models/queries/
from django.db.models import Q
home_trend = ResultForecast.objects.filter(
Q(match__exact=match) &
Q(home_goals__gt=F('away_goals')))
away_trend = ResultForecast.objects.filter(
Q(match__exact=match) &
Q(away_goals__gt=F('home_goals')))
Related
I already calculate, the total of one consummation, now i just want to sum all the consumations
class Consommation(models.Model):
food = models.ManyToManyField(Food)
consomme_le = models.DateTimeField(default=timezone.now, editable=False)
vipcustomer = models.ForeignKey(VipCustomer, models.CASCADE, null=True,
blank=True, verbose_name='Client prestigieux',
related_name='vip_consommations')
to calculate one consummation:
def total(self):
return self.food.aggregate(total=Sum('price'))['total']
Food class :
class Food(models.Model):
nom = models.CharField(max_length=100, verbose_name='Mon menu')
price = models.PositiveIntegerField(verbose_name='Prix')
category = models.ForeignKey(FoodCategory, models.CASCADE,
verbose_name="Categorie")
vipcustomer class:
class VipCustomer(models.Model):
first_name = models.CharField(max_length=150, verbose_name='Prénom')
last_name = models.CharField(max_length=100, verbose_name='Nom')
matricule = models.PositiveIntegerField(verbose_name='Matricule',
default=0)
adresse = models.CharField(max_length=200, verbose_name='Adresse',
blank=True)
telephone = PhoneField()
company = models.CharField(max_length=100, verbose_name='La société')
service = models.CharField(max_length=100, verbose_name='Service',
null=True, blank=True)
numero_badge = models.IntegerField(verbose_name='Numero du badge',
null=True, blank=True)
My goal is to calculate the total of all the consummations.
For a given VipCustomers, you can query with:
my_vip_customer.vip_consommations.aggregate(
total=Sum('food__price')
)['total']
We thus aggregate over the set of related Consommations, and we then aggregate over all the related Foods of these Consommations, and their corresponding price.
If there are no related Consommations, or no related Foods of these Consommations, then the sum will return None, instead of 0. We can add or 0 to convert a None to an 0 here:
my_vip_customer.vip_consommations.aggregate(
total=Sum('food__price')
)['total'] or 0
or for all Customers, we can annotate this with:
VipCustomer.objects.annotate(
total=Sum('vip_consommations__food__price')
)
Here the VipCustomers that arise from this, will have an extra attribute .total that contains the sum of the prices of the related Foods of the related Consommations.
My table named Value has a one to many relationship with the table Country and the table Output_outcome_impact. I have a query that is working fine and gets what I want but then I need to do an average of the value field, but this average needs to be done for each unique id_output_outcome_impact and not the whole query.
class Country(models.Model):
country_name = models.CharField(max_length=255, primary_key=True)
CONTINENTCHOICE = (
('Africa', 'Africa'),
('America', 'America'),
('Asia', 'Asia'),
('Europe', 'Europe'),
('Oceania', 'Oceania')
)
region = models.CharField(max_length=255)
continent = models.CharField(max_length=255, choices=CONTINENTCHOICE)
GDP_per_capita = models.IntegerField(null=True)
unemployment_rate = models.FloatField(null=True)
female_unemployment_rate = models.FloatField(null=True)
litteracy_rate = models.FloatField(null=True)
def __str__(self):
return self.country_name
class OutputOutcomeImpact(models.Model):
output_outcome_impact_name = models.CharField(max_length=255, primary_key=True)
TYPECHOICE = (
('Output', 'Output'),
('Outcome', 'Outcome'),
('Impact', 'Impact'),
)
type = models.CharField(max_length=255, choices=TYPECHOICE)
description = models.TextField()
TARGETGROUP = (
('Standard', 'Standard'),
('Investors', 'Investors'),
('Local authorities and NGOs', 'Local authorities and NGOs'),
)
target_group = models.CharField(max_length=255,choices=TARGETGROUP)
question = models.TextField(null=True, blank=True)
parent_name = models.ForeignKey('self', on_delete=models.PROTECT, null=True, blank=True)
indicator = models.ForeignKey(Indicator, on_delete=models.PROTECT)
def __str__(self):
return self.output_outcome_impact_name
class Activity(models.Model):
activity_name = models.CharField(max_length=255, primary_key=True)
description = models.TextField()
product_service = models.TextField()
output_outcome = models.TextField()
outcome_impact = models.TextField()
output_outcome_impacts = models.ManyToManyField('OutputOutcomeImpact')
countries = models.ManyToManyField('Country')
sectors = models.ManyToManyField('Sector')
def __str__(self):
return self.activity_name
class Value(models.Model):
value_name = models.CharField(max_length=255, primary_key=True)
country = models.ForeignKey(Country, on_delete=models.PROTECT)
id_output_outcome_impact = models.ForeignKey(OutputOutcomeImpact, on_delete=models.PROTECT)
value_has_source = models.ManyToManyField('Source')
value = models.FloatField()
function_name = models.CharField(max_length=255, default = "multiply")
def __str__(self):
return self.value_name
region_values = Value.objects.filter(id_output_outcome_impact__output_outcome_impact_name__in = output_pks, country_id__region = region).exclude(country_id__country_name = country).values()
So the result of the query is available below, and what I would like to achieve is to set the value field to an average of every object that has the same id_output_outcome_impact_id, here Dioxins and furans emissions reduction appears twice so I would like to get the 2 values set as their average.
<QuerySet [{'value_name': 'Waste_to_dioxins', 'country_id': 'Malawi', 'id_output_outcome_impact_id': 'Dioxins and furans emissions reduction', 'value': 0.0003, 'function_name': 'multiply'}, {'value_name': 'Waste_to_dioxins_south_africa', 'country_id': 'South Africa', 'id_output_outcome_impact_id': 'Dioxins and furans emissions reduction', 'value': 150.0, 'function_name': 'multiply'}, {'value_name': 'Households getting electricity per kWh', 'country_id': 'Malawi', 'id_output_outcome_impact_id': 'Households that get electricity', 'value': 0.0012, 'function_name': 'multiply'}, {'value_name': 'Dioxin to disease', 'country_id': 'Malawi', 'id_output_outcome_impact_id': 'Reduction of air pollution related diseases', 'value': 0.31, 'function_name': 'multiply'}]>
I am wondering if django models allow such modification (I went through the doc and saw the annotate function with the average but couldn't make it work for my specific case), that would be nice. Thanks.
region_values = Value.objects.filter(id_output_outcome_impact__output_outcome_impact_name__in = output_pks, country_id__region = region).exclude(country_id__country_name = country).values('id_output_outcome_impact__output_outcome_impact_name').annotate(Avg('value'))
My models:
class Ward(models.Model):
id = models.AutoField(primary_key=True, unique=True)
clinic = models.ForeignKey(Clinic, on_delete=models.CASCADE)
name = models.CharField(max_length=500, default='', blank=True)
description = models.CharField(max_length=2000, default='', blank=True)
bedcapacity = models.IntegerField(default=1)
class Bed(models.Model):
id = models.AutoField(primary_key=True, unique=True)
name = models.CharField(max_length=200, default='',
blank=True, unique=True)
clinic = models.ForeignKey(Clinic, on_delete=models.CASCADE)
ward = models.ForeignKey(Ward, on_delete=models.CASCADE)
occupied = models.BooleanField(default=False)
I'm writing to convert the following pseudocode to django:
from django.db.models import F, Q, When
clinic = Clinic.objects.get(pk=10)
wards = Ward.objects.filter(clinic=clinic)
ward_set = []
for ward in wards:
occupied = len(Bed.objects.filter(clinic = clinic, ward = ward, occupied = True))
total = len(Bed.objects.filter(clinic = clinic, ward = ward))
ward['occupied'] = occupied # The next two lines are pseudocode
ward['total']=total
ward_set.append(ward)
return render(request, 'file.html',
{
'wards': ward_set
})
I believe I should be using annotate, but I'm finding it difficult to understand annotate from the docs.
What about this ?
from django.db.models import Q, Count
ward_set = Ward.objects.filter(clinic=10).annotate(
occupied=Count('bed', filter=Q(bed__occupied=True)),
total=Count('bed')
)
You could see some examples for conditional aggregation here
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')
It is necessary that after the addition of the series, the number of
the series is automatically added, if the administrator forgets to
add, in this way: we take the last created series, from there we take
the series number, and add to this the number of the series 1, and add
to our series! But constantly vylazyut such errors as:
1) lacks the
argument "self", add it (although why it is there at all, it is not
known) and still does not work!
this is my models and SIGNALS
class Series(models.Model):
id = models.AutoField(primary_key=True)
rus_name = models.CharField(max_length=60)
eng_name = models.CharField(max_length=60)
slug = models.SlugField(unique=False)
serial_of_this_series = models.ForeignKey(Serial, on_delete=models.CASCADE, default=True)
season_of_this_series = models.ForeignKey(Season, on_delete=models.CASCADE, default=True)
number_of_series = models.IntegerField(default=0, blank=True, null=True)
description = models.TextField(max_length=700, blank=True, default=None)
size_of_torent_file = models.CharField(max_length=60, default=None)
link_for_dowloand_serie_in_quality_360p = models.CharField(max_length=60, default=None)
link_for_dowloand_serie_in_quality_720p = models.CharField(max_length=60, default=None)
link_for_dowloand_serie_in_quality_1080p = models.CharField(max_length=60, default=None)
rating = models.FloatField(default=0, blank=True)
is_active = models.BooleanField(default=True)
timestamp_rus = models.DateField(auto_now_add=True, auto_now=False)
updated = models.DateTimeField(auto_now_add=False, auto_now=True)
timestamp_eng = models.CharField(max_length=60)
time_of_series = models.DecimalField(max_digits=10, decimal_places=2, default=42)
def get_absolute_url(self):
return reverse('series:post_of_serie', kwargs=
{'serial_slug': self.serial_of_this_series.slug,
'season_slug': self.season_of_this_series.slug,
'series_slug': self.slug})
def __str__(self):
return "%s | %s" % (self.rus_name, self.number_of_series)
class Meta:
ordering = ["-timestamp_rus"]
verbose_name = 'Series'
verbose_name_plural = 'Series'
def series_change_number(sender, **kwargs):
ser = Series.objects.last()
change = ser.number_of_series
number = int(change) + 1
series = Series
series.number_of_series = number
series.save(force_update=True)
pre_save.connect(series_change_number, sender=Series)
ok do this:
def series_change_number(sender, instance, **kwargs):
ser = Series.objects.last()
change = ser.number_of_series
number = int(change) + 1
instance.number_of_series = number
pre_save.connect(series_change_number, sender=Series)
provided you are looking to update the new model object.
Please don't line up your code like that; it makes it very hard to read.
Your problem is here (removing the spaces):
series = Series
That just makes series another name for the Series class. You don't ever instantiate it; to do so you need to actually call it.
series = Series()
... assuming that is actually what you want to do; it's not clear from your code.