Filtering my annotation - python

I have this chunk of code which adds up all the players hurt on one team.
teams = Team.objects.annotate(team_count=Count('Team played for')).order_by('city')
I am having an issue however. It is currently adding all injuries, but I would like to count just the players that are currently injured, or more specifically... where returned=False
Here are my models for a bit more context.
Team models.py
class Team(models.Model):
city = models.CharField(verbose_name='City', max_length=30, null=True, blank=True)
team_name = models.CharField(verbose_name='Team Name', max_length=30, null=True, blank=True)
team_logo = models.ImageField(upload_to='images/', null=True, blank=True)
team_affiliation = models.ForeignKey('self', null=True, blank=True)
def __unicode__(self):
return u'%s %s' % (self.city, self.team_name)
EDIT added player models.py
class Player(models.Model):
first_name = models.CharField(verbose_name='First Name', max_length=30, null=True, blank=True)
last_name = models.CharField(verbose_name='Last Name', max_length=30, null=True, blank=True)
team = models.ForeignKey(Team, related_name='Team played for')
position = models.ForeignKey(Position, related_name="Position")
pob = models.CharField(verbose_name='Place of Birth', max_length=100, null=True, blank=True)
dob = models.DateField()
age = models.IntegerField(null=True, blank=True)
height = models.CharField(verbose_name='Height', max_length=10, null=True, blank=True)
weight = models.CharField(verbose_name='Weight', max_length=10, null=True, blank=True)
drafted_by = models.ForeignKey(Team, related_name='drafted by', null=True, blank=True)
def __unicode__(self):
return u'%s %s' % (self.first_name, self.last_name)
Injury models.py
class PlayerInjury(models.Model):
player = models.ForeignKey(Player)
injury_type = models.ForeignKey(Injury)
injury_date = models.DateField(verbose_name='Injured On', null=True, blank=True)
description = models.CharField(verbose_name='Description', max_length=180, null=True, blank=True)
status = models.ForeignKey(Status)
projected_return = models.DateField(verbose_name='Projected Return Date', null=True, blank=True)
hide = models.BooleanField(default=False)
returned = models.BooleanField(default=False)
timestamp = models.DateTimeField(auto_now_add=True)
source = models.URLField(max_length=200, null=True, blank=True)
source_label = models.CharField(null=True, blank=True, max_length=200)
def __unicode__(self):
return u'%s - %s' % (self.player, self.injury_type)
Is there a way I can filter the annotation so that it will only count the currently injured players?

Just filter before calling annotate: .filter(player__playerinjury__returned=False).annotate(...).

Related

Serialize same level object from Many to many field

I have to serialize spare instance from spare variety many to many field.
Models.py
class SpareVariety(models.Model):
quality = models.ForeignKey(Quality, max_length=255, on_delete=models.CASCADE, null=True, blank=True)
variety_name = models.CharField(max_length=255, null=True, blank=True)
property = models.ForeignKey(SpareProperty, null=True, blank=True, on_delete=models.CASCADE)
purchase_price = models.PositiveIntegerField(help_text="in INR", blank=True, null=True)
retail_price = models.FloatField(help_text="All values in INR", blank=True, null=True)
dealer_price = models.FloatField(help_text="All values in INR", blank=True, null=True)
stock_available = models.PositiveIntegerField(blank=True, null=True,default=True)
spare_costing = models.ForeignKey(SpareCosting, on_delete=models.CASCADE, blank=True, null=True)
spare_discount = models.ForeignKey(Discount, on_delete=models.CASCADE, blank=True, null=True)
is_available = models.BooleanField(default=False)
date_added = models.DateTimeField(auto_now=True)
date_updated = models.DateTimeField(auto_now_add=True)
class Spare(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE)
spare_variety = models.ManyToManyField(SpareVariety, related_name='spare_varieties', null=True, blank=True)
name = models.CharField(max_length=255, help_text="Enter the name of spare (Ex:Display, Speakers)")
type = models.ForeignKey(Type, blank=True, null=True, on_delete=models.CASCADE)
date_added = models.DateTimeField(auto_now=True)
date_updated = models.DateTimeField(auto_now_add=True)
def __str__(self):
return '%s - %s' % (self.product.name, self.name)
Serialize the spare model from spare variety serializer
serializers.py
class SpareVarietySerializer(serializers.HyperlinkedModelSerializer):
spare_costing= SpareCostingSerializer(many=False, read_only=False)
spare_discount = DiscountSerializer(many=False, read_only=False)
quality = QualitySerializer(many=False, read_only=False)
property = SparePropertySerializer(many=False, read_only=False)
spare_name = serializers.CharField(read_only=True, source="spare.name")
class Meta:
model = SpareVariety
fields = ['id','quality','variety_name','purchase_price','spare_name','retail_price','property', 'dealer_price', 'stock_available','spare_costing','spare_discount','is_available', 'date_added', 'date_updated',]

Post returns 1364, Field 'ADD' doesn't have a default value

THe error upon clicking the POST button on Djangorest Form
The serializer:
class CreatePolicyBenefitsSerializer(serializers.ModelSerializer):
class Meta:
model = Policy
fields = ('company','name','benefits','price')
The views:
class CreatePolicyBenefits(CreateAPIView):
queryset = Policy.objects.all()
serializer_class = CreatePolicyBenefitsSerializer
The Policy Model
``
class Policy(TimeStampedModel):
POLICY_CHOICES = (
('life', 'Life'),
('health', 'Health'),
('home', 'Home'),
('car', 'Car'),
('vul', 'VUL'),
)
PREMIUM_INTERVALS = (
('one_time', 'One Time'),
('annual', 'Annual'),
('semi_annual', 'Semi Annual'),
('quarterly', 'Quarterly'),
('monthly', 'Monthly')
)
company = models.ForeignKey(
'Company', related_name='Policies', on_delete=models.CASCADE,
null=True, blank=True)
name = models.CharField(max_length=255, blank=True, null=True, default="")
description = models.TextField(blank=True, null=True, default="")
benefits = models.JSONField(null=True, blank=True)
price = models.DecimalField(max_digits=10, decimal_places=2, default=0)
category = models.CharField(
max_length=64, blank=True, null=True, choices=POLICY_CHOICES, default="")
premium_details = models.CharField(max_length=255, blank=True, null=True)
policy_details = models.CharField(max_length=255, blank=True, null=True)
available_premium_interval = models.CharField(
max_length=64, blank=True, null=True, choices=PREMIUM_INTERVALS)
icon_name = models.CharField(max_length=32, blank=True, null=True)
icon_file = models.FileField(
upload_to=upload_policy_icon, blank=True, null=True)
primary_color = models.CharField(max_length=32, blank=True, null=True)
# file=models.FilePathField(path=os.path.join(settings.MEDIA_ROOT, 'media'))
adminupload=models.FileField(upload_to=pdf_path,max_length=None)
pdfname=models.CharField(max_length=255, blank=True, null=True)
class Meta:
app_label = samplename
def __str__(self):
return '[%s] %s-%s' % (self.id, self.company, self.name)
Here the form
Is it possible when I hit POST button, the data can be displayed on the form? Thanks

Filter one-to-many relationship

I'm using django-filter and I would like to ask you if it could filter one to many reliontionship because I did not found any doc or example even on StackOverflow., here are the model, the filter and the view
class Aliens(models.Model):
class Meta:
db_table = 'aliens'
verbose_name = ('Introduction Event')
verbose_name_plural = ('Introuction Events')
ordering = ['alien']
alien = models.OneToOneField(Taxonomy, verbose_name=u"Non-indigenous Species",
on_delete=models.CASCADE, null=True, blank=True)
#SpeciesName = models.CharField(max_length=100, verbose_name=u"Species Name", blank=True, null=True)
group = models.OneToOneField(Ecofunctional, verbose_name=u"Ecofunctional Group", on_delete=models.CASCADE,
blank=True, null=True, default='')
firstsight = models.IntegerField(('First Mediterranean Sighting'), choices=YEAR_CHOICES, blank=True, null=True)
med_citation = models.ForeignKey(biblio, verbose_name=u"Mediterranean first citation", on_delete=models.CASCADE,
null=True, blank=True)
origin = models.OneToOneField(Origin, on_delete=models.CASCADE, blank=True, null=True, default='',
verbose_name=u"Origin")
status = models.OneToOneField(SuccessType, on_delete=models.CASCADE, blank=True, null=True, default='',
verbose_name=u"Establishement")
created_by = CurrentUserField()
created_at = models.DateField('date of inclusion', blank=True, null=True, default=datetime.datetime.now())
photo = models.ImageField(upload_to='photos', blank=True, null=True)
vector = models.ManyToManyField(vectors, verbose_name=u"Vectors/Pathways")
updated_at = models.DateField('date of updating', blank=True, null=True, default=datetime.datetime.now())
updated_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name='%(class)s_requests_updated',
default=CurrentUserField(), null=True)
notes = models.TextField(verbose_name='Notes', blank=True, null=True)
db_status = StateField(verbose_name='Species Status in the Db', blank=True, null=True)
def __str__(self): # __unicode__ on Python 2
return self.alien.SpeciesName
class Distributions(models.Model):
class Meta:
db_table = 'distributions'
verbose_name = ('verified occurence')
verbose_name_plural = ('verified occurences')
alien = models.ForeignKey(Aliens, verbose_name=u"Non-Indeginous Species", related_name='distributions',
on_delete=models.CASCADE, null=True, blank=True)
country = models.OneToOneField(Country, on_delete=models.CASCADE, verbose_name='Country', blank=True, null=True)
seas = models.OneToOneField(regionalseas, on_delete=models.CASCADE, verbose_name='Regional Sea', blank=True,
null=True)
MSFD = models.OneToOneField(MSFD, on_delete=models.CASCADE, verbose_name='MSFD/EcAp Sub-region', blank=True,
null=True)
area1stSighting = models.DateField('First Areas Sighting', blank=True, null=True, default=datetime.datetime.now())
AreaSuccessType = models.OneToOneField(SuccessType, on_delete=models.CASCADE,
verbose_name='Area Establishement/Success', blank=True, null=True)
Area_citation = models.ForeignKey(biblio, verbose_name=u"Area first citation", on_delete=models.CASCADE, null=True,
blank=True)
created_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name='%(class)s_requests_created',
default='')
created_at = models.DateField('date of Edition', blank=True, null=True, default=datetime.datetime.now())
updated_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name='%(class)s_requests_updated',
default='')
updated_at = models.DateField('date of updating', blank=True, null=True, default=datetime.datetime.now())
notes = models.TextField(verbose_name='Notes', blank=True, null=True)
dverification = StateField(verbose_name='Validated ')
def __str__(self): # __unicode__ on Python 2
return self.alien.SpeciesName
class AliensFilter(django_filters.FilterSet):
country = filters.ModelChoiceFilter(label='Country', queryset=Country.objects.all())
msfd = filters.ModelChoiceFilter(label='MSF/EcAp Subregions', queryset=MSFD.objects.all())
regseas = filters.ModelChoiceFilter(label='Regional Seas', queryset=regionalseas.objects.all())
vector = filters.ModelChoiceFilter(label='Vectors/Pathway', queryset=vectors.objects.all())
Species = filters.ModelChoiceFilter(label='Species Name', queryset=Taxonomy.objects.all())
class Meta:
model = Aliens
fields = (
'Species', 'group', 'origin', 'firstsight', 'status', 'vector', 'country', 'msfd', 'regseas')
def search(request):
Aliens_list = Aliens.objects.all().select_related('origin', 'status', 'group', 'Taxonomy')
aliens_filter = AliensFilter(request.GET, queryset=Aliens_list)
# return render(request, 'mamias/list.html', {'filter': aliens_filter})
return render(request, 'mamias/list2.html', {'filter': aliens_filter})
How could I filter based on country for example?
There is no direct relationship between the Aliean and Country models. You would need to instead filter by country through the distributions relationship.
from django_filters import FilterSet, filters
class AlienFilter(FilterSet):
country = filters.ModelChoiceFilter(
field_name='distributions__country',
queryset=Country.objects.all(),
)

ValueError: save() prohibited to prevent data loss due to unsaved related object

Hi I am recreating a website in django and this happens...
Django throw this error,
ValueError: save() prohibited to prevent data loss due to unsaved related object 'fk_deal'.
even though I have saved the foreign key related object. This is the view part.
if request.method == "POST":
deal = DEAL()
name = request.POST.get('name')
revenue_2013 = request.POST.get('revenue_2013')
if project_name:
print project_name
deal.name = project_name
deal.save()
print deal.id # prints None
# financials 2013
if revenue_2013:
fin = DEALFINANCIALINFORMATION.objects.create(
financial_category_amount=revenue_2013,
financial_year='2013',
fk_deal = deal,
financial_category_id=1,
)
These are the models....
class DEAL(models.Model):
id = models.BigIntegerField(db_column='ID', primary_key=True) # Field name made lowercase.
company_name = models.CharField(max_length=33L, db_column=u'COMPANY_NAME', blank=True)
investmentrequired = models.FloatField(null=True, blank=True)
is_deleted = MySQLBooleanField(db_column=u'IS_DELETED', blank=True, default=None)
name = models.CharField(max_length=33L, db_column=u'NAME', blank=True)
photo = models.CharField(max_length=66L, db_column=u'PHOTO', blank=True)
status = models.CharField(max_length=85L, db_column=u'STATUS', blank=True)
timestamp = models.DateTimeField(null=True, db_column=u'TIMESTAMP', blank=True)
teaser = models.TextField(db_column=u'TEASER', blank=True)
currency_id = models.BigIntegerField(null=True, db_column=u'CURRENCY_ID', blank=True)
description = models.TextField(db_column=u'DESCRIPTION', blank=True)
country = models.ForeignKey('COUNTRIES', null=True, db_column=u'COUNTRY_ID', blank=True)
sector = models.ForeignKey('SECTORS', null=True, db_column=u'SECTOR_ID', blank=True)
type = models.ForeignKey('TYPES', null=True, db_column=u'TYPE_ID', blank=True)
username = models.CharField(max_length=85L, db_column=u'USERNAME', blank=True)
user = models.ForeignKey('USER', null=True, db_column=u'USER_ID', blank=True)
hitcounter = models.BigIntegerField(null=True, db_column=u'HITCOUNTER', blank=True)
approx_usd = models.DecimalField(decimal_places=2, null=True, max_digits=19, db_column=u'approxUSD', blank=True)
userdeal_id = models.BigIntegerField(null=True, db_column=u'USERDEAL_ID', blank=True)
is_featuredeal = MySQLBooleanField(db_column=u'IS_FEATUREDEAL', blank=True, default=None)
basic_company_email = models.CharField(max_length=33L, db_column=u'BASIC_COMPANY_EMAIL', blank=True)
basic_company_name = models.CharField(max_length=33L, db_column=u'BASIC_COMPANY_NAME', blank=True)
basic_company_phone = models.CharField(max_length=33L, db_column=u'BASIC_COMPANY_PHONE', blank=True)
basic_company_website = models.CharField(max_length=33L, db_column=u'BASIC_COMPANY_WEBSITE', blank=True)
basic_elevator_pitch = models.TextField(db_column=u'BASIC_ELEVATOR_PITCH', blank=True)
basic_premoney_evaluation = models.DecimalField(decimal_places=2, null=True, max_digits=19, db_column=u'BASIC_PREMONEY_EVALUATION', blank=True)
basic_question_1 = models.TextField(db_column=u'BASIC_QUESTION_1', blank=True)
basic_question_2 = models.TextField(db_column=u'BASIC_QUESTION_2', blank=True)
basic_question_3 = models.TextField(db_column=u'BASIC_QUESTION_3', blank=True)
basic_summary = models.TextField(db_column=u'BASIC_SUMMARY', blank=True)
basic_total_offering_amount = models.DecimalField(decimal_places=2, null=True, max_digits=19, db_column=u'BASIC_TOTAL_OFFERING_AMOUNT', blank=True)
is_company = MySQLBooleanField(db_column=u'IS_COMPANY', blank=True, default=None)
is_posted = MySQLBooleanField(db_column=u'IS_POSTED', blank=True, default=None)
is_visible = MySQLBooleanField(db_column=u'IS_VISIBLE', blank=True, default=None)
other_company_milestones = models.TextField(db_column=u'OTHER_COMPANY_MILESTONES', blank=True)
projectname = models.CharField(max_length=33L, db_column=u'PROJECTNAME', blank=True)
basicdealstage = models.ForeignKey('DEALSTAGES', null=True, db_column=u'BASICDEALSTAGE_ID', blank=True)
basic_security_type = models.ForeignKey('SECURITYTYPES', null=True, db_column=u'BasicSecurityType_ID', blank=True)
is_public = MySQLBooleanField(db_column=u'IS_PUBLIC', blank=True, default=None)
profile_completed = models.BigIntegerField(null=True, db_column=u'PROFILE_COMPLETED', blank=True)
is_closed = MySQLBooleanField(db_column=u'IS_CLOSED', blank=True, default=None)
first_step_completed = models.BigIntegerField(null=True, db_column=u'FIRST_STEP_COMPLETED', blank=True, default=0L)
second_step_completed = models.BigIntegerField(null=True, db_column=u'SECOND_STEP_COMPLETED', blank=True)
third_step_completed = models.BigIntegerField(null=True, db_column=u'THIRD_STEP_COMPLETED', blank=True)
class Meta:
db_table = u'DEAL'
def __unicode__(self):
if self.name:
return self.name
else:
return "No name"
class DEALFINANCIALINFORMATION(models.Model):
id = models.BigIntegerField(db_column='ID', primary_key=True) # Field name made lowercase.
financial_category_amount = models.DecimalField(decimal_places=2, null=True, max_digits=19, db_column=u'FINANCIAL_CATEGORY_AMOUNT', blank=True)
financial_year = models.CharField(max_length=33L, db_column=u'FINANCIAL_YEAR', blank=True)
de_al_id = models.BigIntegerField(null=True, db_column=u'DEAl_ID', blank=True)
financial_category_id = models.BigIntegerField(null=True, db_column=u'FINANCIAL_CATEGORY_ID', blank=True)
fk_deal = models.ForeignKey('DEAL', null=True, blank=True)
class Meta:
db_table = u'DEAL_FINANCIAL_INFORMATION'
The database was created from an existing MySQL database....
I send the data to the view using jquery POST....
I can't seem to find out what the problem is. Also even after saving the model if I print the id field it returns None instead....
Can somebody help me?

Django planmember_set issue

I have a question that I hope someone can help me with. I'm using a form to have the user select a "plan". Now I want to list all the members in the plan, in the form. I have a function 'get_owners' that grabs all the members in the plan, by using this function:
def get_owners(self):
owners = self.planmember_set.filter(ownership_type__code__in=["primary","joint"])
return owners
Only problem is that I get an output of:
[<PlanMember: Doe, John (Primary)>, <PlanMember: Doe, Jane(Joint Subscriber)>, etc]
Now is there a way for me to just show their names and the member type (the words in brackets)?
A bit of background code.
Here is my views.py:
if request.POST:
form = PlanMaturityYearForm(Plan.objects.all().filter(profile = p), request.POST)
if form.is_valid():
selected_plan = form.cleaned_data['plans']
plan = get_object_or_404(Plan, pk=selected_plan.pk)
investment_list = Investment.objects.all().filter(Q(plan = plan)).order_by('maturity_date')
context['investment_list'] = investment_list
context['plan'] = plan
context['today'] = now
context['current_yr'] = current_year
context['next_yr'] = next_year
context['show_report'] = True
else:
form = PlanMaturityYearForm(Plan.objects.all().filter(profile = p))
context['form'] = form
return render_to_response('reports/planmaturities_year.html', RequestContext(request, context))
And my forms.py:
class PlanMaturityYearForm(forms.Form):
def __init__(self, plans, *args, **kwargs):
super(PlanMaturityYearForm, self).__init__(*args, **kwargs)
self.fields['plans'] = forms.ModelChoiceField(
plans,
required=True,
widget=forms.Select(attrs={'size': 20}),
error_messages={'required':'Please select the plan you wish to build the report for',}
)
Edit:
models.py
class Plan(models.Model):
old_id = models.IntegerField(null=True)
closed = models.BooleanField(default=False, blank=True)
closed_date = models.DateField(null=True)
profile = models.ForeignKey(Profile, default=False)
plan_type = models.ForeignKey(PlanType)
ownership_type = models.ForeignKey(OwnershipType)
status = models.PositiveSmallIntegerField(max_length=2, default=PLAN_OPEN)
timestamp = models.DateTimeField(auto_now_add=True, null=True, blank=True)
notes = HTMLField(blank=True, null=True)
bank = models.CharField(max_length=50, blank=True, null=True)
account = models.CharField(max_length=50, blank=True, null=True)
transit = models.CharField(max_length=50, blank=True, null=True)
objects = PlanManager()
class Profile(models.Model):
old_id = models.IntegerField(null=True, blank=True)
label = models.CharField(max_length=255, blank=True, verbose_name='Profile label/description')
location = models.ForeignKey(Location, null=True, blank=True)
client = models.BooleanField(default=False, blank=True)
corp = models.BooleanField(default=False, blank=True)
noncorp = models.BooleanField(default=False, blank=True)
timestamp = models.DateTimeField(auto_now_add=True, default=False)
bak_agent_id = models.CharField(max_length=10, null=True, blank=True)
agent = models.ForeignKey(Agent, related_name='profiles')
check1 = models.BooleanField(default=False, blank=True)
incorp_date = models.DateField(null=True, blank=True)
corp_records = models.BooleanField(default=False, blank=True)
articles_of_incorp = models.BooleanField(default=False, blank=True)
other_corp_articles = models.CharField(max_length=50, null=True, blank=True)
bin = models.CharField(max_length=50, null=True, blank=True, verbose_name='BIN')
phone = models.CharField(max_length=25, null=True)
registration = models.CharField(max_length=45, null=True, blank=True)
num_sigs = models.IntegerField(max_length=1, null=True, blank=True,
verbose_name='Number of signatures required to transaction the account')
charity = models.BooleanField(default=False, blank=True)
donations_solicited = models.BooleanField(default=False, blank=True)
ownership_type = models.CharField(max_length=45, null=True, blank=True)
ownership_other = models.CharField(max_length=45, null=True, blank=True) #work around for other business type selction
business_nature = models.CharField(max_length=45, null=True, blank=True)
date_incept = models.DateField(null=True, blank=True)
bind_power = models.BooleanField(default=False, blank=True)
reg_documents = models.BooleanField(default=False, blank=True)
other_documents = models.CharField(max_length=50, null=True, blank=True)
reg_number = models.CharField(max_length=45, null=True, blank=True)
tax_number = models.CharField(max_length=45, null=True, blank=True)
phone = models.CharField(max_length=25, null=True, blank=True)
fax = models.CharField(max_length=25, null=True, blank=True)
email = models.CharField(max_length=100, null=True, blank=True)
You can use values_list:
owners = self.planmember_set.filter(
ownership_type__code__in=["primary","joint"]
).values_list('name', 'type')
def get_owners(self):
owners = self.planmember_set.filter(ownership_type__code__in=["primary","joint"]).values_list('name_field', 'ownership_type__code')
return owners
Write where and how you use get_owners if not correct.

Categories

Resources