Django function, obtain result for show in view - python

I have a function in a django model, this function is for calculating the two fields, but how I can obtain the function result,for show this in a django view
class Player(models.Model):
team = models.ForeignKey(Team)
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
gp = models.IntegerField(max_length=2) #games played
mp = models.IntegerField(max_length=4) #minutes played
def mpg(self): #minutes per game
return self.mp/self.gp
def __unicode__(self):
return self.first_name+' '+self.last_name
When I run "python manage.py shell" and try to pull up a player's
"mpg", I get:
>>> p = Player.objects.get(last_name='Durant')
>>> p
<Player: Kevin Durant>
>>> p.mp
1027
>>> p.gp
27
>>> p.mpg
<bound method Player.mpg of <Player: Kevin Durant>>

mpg is a method, and like all methods in Python, you need to actually call it to get its result:
p.mpg()

Related

How to update queryset value in django?

I have written a python script in my project. I want to update the value of a field.
Here are my modes
class News_Channel(models.Model):
name = models.TextField(blank=False)
info = models.TextField(blank=False)
image = models.FileField()
website = models.TextField()
total_star = models.PositiveIntegerField(default=0)
total_user = models.IntegerField()
class Meta:
ordering = ["-id"]
def __str__(self):
return self.name
class Count(models.Model):
userId = models.ForeignKey(User, on_delete=models.CASCADE)
channelId = models.ForeignKey(News_Channel, on_delete=models.CASCADE)
rate = models.PositiveIntegerField(default=0)
def __str__(self):
return self.channelId.name
class Meta:
ordering = ["-id"]
This is my python script:
from feed.models import Count, News_Channel
def run():
for i in range(1, 11):
news_channel = Count.objects.filter(channelId=i)
total_rate = 0
for rate in news_channel:
total_rate += rate.rate
print(total_rate)
object = News_Channel.objects.filter(id=i)
print(total_rate)
print("before",object[0].total_star,total_rate)
object[0].total_star = total_rate
print("after", object[0].total_star)
object.update()
After counting the total_rate from the Count table I want to update the total star value in News_Channel table. I am failing to do so and get the data before the update and after the update as zero. Although total_rate has value.
The problem
The reason why this fails is because here object is a QuerySet of News_Channels, yeah that QuerySet might contain exactly one News_Channel, but that is irrelevant.
If you then use object[0] you make a query to the database to fetch the first element and deserialize it into a News_Channel object. Then you set the total_star of that object, but you never save that object. You only call .update() on the entire queryset, resulting in another independent query.
You can fix this with:
objects = News_Channel.objects.filter(id=i)
object = objects[0]
object.total_star = total_rate
object.save()
Or given you do not need any validation, you can boost performance with:
News_Channel.objects.filter(id=i).update(total_star=total_rate)
Updating all News_Channels
If you want to update all News_Channels, you actually better use a Subquery here:
from django.db.models import OuterRef, Sum, Subquery
subq = Subquery(
Count.objects.filter(
channelId=OuterRef('id')
).annotate(
total_rate=Sum('rate')
).order_by('channelId').values('total_rate')[:1]
)
News_Channel.objects.update(total_star=subq)
The reason is that object in your case is a queryset, and after you attempt to update object[0], you don't store the results in the db, and don't refresh the queryset. To get it to work you should pass the field you want to update into the update method.
So, try this:
def run():
for i in range(1, 11):
news_channel = Count.objects.filter(channelId=i)
total_rate = 0
for rate in news_channel:
total_rate += rate.rate
print(total_rate)
object = News_Channel.objects.filter(id=i)
print(total_rate)
print("before",object[0].total_star,total_rate)
object.update(total_star=total_rate)
print("after", object[0].total_star)
News_Channel.total_star can be calculated by using aggregation
news_channel_obj.count_set.aggregate(total_star=Sum('rate'))['total_star']
You can then either use this in your script:
object.total_star = object.count_set.aggregate(total_star=Sum('rate'))['total_star']
Or if you do not need to cache this value because performance is not an issue, you can remove the total_star field and add it as a property on the News_Channel model
#property
def total_star(self):
return self.count_set.aggregate(total_star=Sum('rate'))['total_star']

Django Integrated Test Passing When it Should Fail

I'm in the process of creating an assessment system using Django; however, I have an integrated test that passes and I'm not sure as to why (it should be failing). In the test, I set the grade field of the bobenrollment object to "Excellent". As you can see from the models below, the Enrollment model doesn't have a grade field (none of the models do). I was under the impression that dot notation of model objects would access the model fields (I'm probably incorrect about this). I don't want to write ineffective tests, so I would like to know what makes this test pass and what I should do to make it break. Thanks!
class ClassAndSemesterModelTest(TestCase):
def add_two_classes_to_semester_add_two_students_to_class(self):
first_semester = Semester.objects.create(text='201530')
edClass = EdClasses.objects.create(name='EG 5000')
edClass2 = EdClasses.objects.create(name='EG 6000')
first_semester.classes.add(edClass)
first_semester.classes.add(edClass2)
bob = Student.objects.create(name="Bob DaBuilder")
jane = Student.objects.create(name="Jane Doe")
bobenrollment = Enrollment.objects.create(student=bob, edclass=edClass)
janeenrollment = Enrollment.objects.create(student=jane,edclass=edClass)
bobenrollment2 = Enrollment.objects.create(student=bob,edclass=edClass2)
janeenrollment2 = Enrollment.objects.create(student=jane,edclass=edClass2)
def test_students_link_to_enrollments(self):
self.add_two_classes_to_semester_add_two_students_to_class()
edclass1 = EdClasses.objects.get(name="EG 5000")
bob = Student.objects.get(name="Bob DaBuilder")
#The three lines below are the subject of my question
bobenrollment = Enrollment.objects.get(edclass=edclass1, student=bob)
bobenrollment.grade = "Excellent"
self.assertEqual(bobenrollment.grade, "Excellent")
And the models below:
from django.db import models
class Student(models.Model):
name = models.TextField(default="")
def __str__(self):
return self.name
#TODO add models
class EdClasses(models.Model):
name = models.TextField(default='')
students = models.ManyToManyField(Student, through="Enrollment")
def __str__(self):
return self.name
class Semester(models.Model):
text = models.TextField(default='201530')
classes = models.ManyToManyField(EdClasses)
def __str__(self):
return self.text
class Enrollment(models.Model):
student = models.ForeignKey(Student)
edclass = models.ForeignKey(EdClasses)
Requirements.txt
beautifulsoup4==4.4.1
Django==1.5.4
ipython==3.1.0
LiveWires==2.0
nose==1.3.3
Pillow==2.7.0
projectname==0.1
pyperclip==1.5.11
pytz==2015.2
requests==2.10.0
selenium==2.53.6
six==1.9.0
South==1.0.2
swampy==2.1.7
virtualenv==1.11.5
I was under the impression that dot notation of model objects would access the model fields (I'm probably incorrect about this)
You're correct about this. What you're not taking into account is the fact that you can dynamically add properties to python objects. For instance:
In [1]: class MyClass():
...: pass
...:
In [2]: a = MyClass()
In [3]: a.im_a_property = 'hello'
In [4]: print a.im_a_property
hello
As you can see, the a instance will have the im_a_propery property even though it's not defined by the class. The same applies for the following line in your code:
bobenrollment.grade = "Excellent"
Django models override this behavior so you can seamlessly get DB values as properties of your model instance, but the instance is just a regular python object.
If you want to test the grade property gets saved correctly, you should modify your test to add the value of grade when creating the record and making sure the instance you assert against is the one you read from your DB (i.e. not modifying it beforehand).

objects.all() not returning any objects in Django

I have the following models in models.py:
from django.contrib.auth.models import User
from django.db import models
class Usertypes(models.Model):
user = models.OneToOneField(User)
usertype = models.TextField()
def __unicode__(self):
return self.user_name
class Games(models.Model):
name = models.CharField(max_length=100,unique=True)
category = models.CharField(max_length=100)
url = models.URLField()
developer = models.ForeignKey(User)
price = models.FloatField()
def __unicode__(self):
return self.name
class Scores(models.Model):
game = models.ForeignKey(Games)
player = models.ForeignKey(User)
registration_date = models.DateField(auto_now=False, auto_now_add=False)
highest_score = models.PositiveIntegerField(null=True,blank=True)
most_recent_score = models.PositiveIntegerField(null=True,blank=True)
def __unicode__(self):
return self.most_recent_score
I am now creating objects of all 3 types. I have created some User and Games objects earlier, so when I run the following commands, the outputs as given below are obtained:
>>> u = User.objects.all()
>>> u.count()
5
>>> g = Games.objects.all()
>>> g.count()
9
Now, I am trying to create some Scores objects using the following commands. The outputs are given below:
>>> fifa = Games.objects.get(pk=18)
>>> user1 = User.objects.get(id=2)
>>> user2 = User.objects.get(id=7)
>>> user3 = User.objects.get(id=9)
>>> p1 = Scores(game=fifa,player=user1,registration_date='2015-01-29')
>>> p2 = Scores(game=fifa,player=user2,registration_date='2014-12-21')
>>> p3 = Scores(game=fifa,player=user3,registration_date='2015-01-29')
>>> user1
<User: admin>
>>> fifa
<Games: Games object>
>>> p1
<Scores: Scores object>
>>> p2
<Scores: Scores object>
>>> p3
<Scores: Scores object>
The problem is:
>>> s = Scores.objects.all()
>>> s.count()
0
I don't understand why, despite having created 3 Scores objects, Scores.objects.all() returns nothing. Can someone help? Thanks in advance!!
You never inserted the scores to the database (so of course the database can't give them back to you):
p1.save() # This will save the object to the database
Note that you could also use Scores.objects.create(...) (instead of Score()). This will initialize an object and immediately save it to the database:
p1 = Scores.objects.create(game=fifa,player=user1,registration_date='2015-01-29')
Now these methods would result in three queries being made to the database, which isn't ideal (you hit the roundtrip latency 3 times).
Fortunately, you can easily optimize and make a single query using bulk_create:
Scores.objects.bulk_create([
Scores(game=fifa,player=user1,registration_date='2015-01-29')
Scores(game=fifa,player=user2,registration_date='2014-12-21')
Scores(game=fifa,player=user3,registration_date='2015-01-29')
])
Make sure you are running .save(), which actually saves the item in the database. Without it, you aren't saving anything in the database therefore you get nothing when you retrieve objects from the database

How does django one-to-one relationships map the name to the child object?

Apart from one example in the docs, I can't find any documentation on how exactly django chooses the name with which one can access the child object from the parent object. In their example, they do the following:
class Place(models.Model):
name = models.CharField(max_length=50)
address = models.CharField(max_length=80)
def __unicode__(self):
return u"%s the place" % self.name
class Restaurant(models.Model):
place = models.OneToOneField(Place, primary_key=True)
serves_hot_dogs = models.BooleanField()
serves_pizza = models.BooleanField()
def __unicode__(self):
return u"%s the restaurant" % self.place.name
# Create a couple of Places.
>>> p1 = Place(name='Demon Dogs', address='944 W. Fullerton')
>>> p1.save()
>>> p2 = Place(name='Ace Hardware', address='1013 N. Ashland')
>>> p2.save()
# Create a Restaurant. Pass the ID of the "parent" object as this object's ID.
>>> r = Restaurant(place=p1, serves_hot_dogs=True, serves_pizza=False)
>>> r.save()
# A Restaurant can access its place.
>>> r.place
<Place: Demon Dogs the place>
# A Place can access its restaurant, if available.
>>> p1.restaurant
So in their example, they simply call p1.restaurant without explicitly defining that name. Django assumes the name starts with lowercase. What happens if the object name has more than one word, like FancyRestaurant?
Side note: I'm trying to extend the User object in this way. Might that be the problem?
If you define a custom related_name then it will use that, otherwise it will lowercase the entire model name (in your example .fancyrestaurant). See the else block in django.db.models.related code:
def get_accessor_name(self):
# This method encapsulates the logic that decides what name to give an
# accessor descriptor that retrieves related many-to-one or
# many-to-many objects. It uses the lower-cased object_name + "_set",
# but this can be overridden with the "related_name" option.
if self.field.rel.multiple:
# If this is a symmetrical m2m relation on self, there is no reverse accessor.
if getattr(self.field.rel, 'symmetrical', False) and self.model == self.parent_model:
return None
return self.field.rel.related_name or (self.opts.object_name.lower() + '_set')
else:
return self.field.rel.related_name or (self.opts.object_name.lower())
And here's how the OneToOneField calls it:
class OneToOneField(ForeignKey):
... snip ...
def contribute_to_related_class(self, cls, related):
setattr(cls, related.get_accessor_name(),
SingleRelatedObjectDescriptor(related))
The opts.object_name (referenced in the django.db.models.related.get_accessor_name) defaults to cls.__name__.
As for
Side note: I'm trying to extend the
User object in this way. Might that be
the problem?
No it won't, the User model is just a regular django model. Just watch out for related_name collisions.

How do you add a model method to an existing class within an interactive session (in iPython)?

I have a basic model:
class Person(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
state = USStateField()
I start up an iPython session with:
$ python manage.py shell
>>> from app.models import Person
How do I add this model method within the iPython session?
>>> def is_midwestern(self):
... "Returns True if this person is from the Midwest."
... return self.state in ('IL', 'WI', 'MI', 'IN', 'OH', 'IA', 'MO')
>>> person = Person.objects.filter(last_name='Franklin')
>>> person.is_midwestern
True
I want to be able to test these model methods without having to add the method to the models.py file and then restarting the iPython shell session.
I seem to be doing something wrong because when I add a new model method in an interactive session, it doesn't seem to be linked to the class like it does when the model method is defined in a file.
So if I created the model method as above and attempted to use it.
e.g.
' >>> person = Person.objects.filter(last_name='Franklin')
>>> person.is_midwestern
'Person' object has no attribute'is_midwestern'`
why can't you just do this
Person.is_midwestern = is_miswestern e.g.
>>> class Person:
... def __init__(self): self.mid = True
...
>>> def is_midwestern(self): return self.mid
...
>>> Person.is_midwestern = is_midwestern
>>> p = Person()
>>> p.is_midwestern()
True
>>>
The accepted answer gave me an error, but from this blog post, I used the following method and it worked.
from types import MethodType
Person.is_midwestern = MethodType(is_midwestern, p)

Categories

Resources