Let's say I have the following Django model:
class Person(models.Model):
SHIRT_SIZES = (
(0, 'Small'),
(1, 'Medium'),
(2, 'Large'),
)
name = models.CharField(max_length=60)
shirt_size = models.IntegerField(choices=SHIRT_SIZES)
I can create create a Person instance and get the shirt_size display value very easily:
john = Person(name="John", shirt_size=2)
john.shirt_size # 2
john.get_shirt_size_display() # 'Medium'
How can I do this the other way? That is, given a shirt size of Medium, how can I get the integer value? I there a method for that or should I write my own method on the Person object like so:
class Person(models.Model):
...
#staticmethod
def get_shirt_size_key_from_display_value(display_value):
for (key, value) in Person.SHIRT_SIZES:
if value == display_value:
return key
raise ValueError(f"No product type with display value {display_value}")
The docs recommend the following:
class Person(models.Model):
SMALL = 0
MEDIUM = 1
LARGE = 2
SHIRT_SIZES = (
(SMALL, 'Small'),
(MEDIUM, 'Medium'),
(LARGE, 'Large'),
)
name = models.CharField(max_length=60)
shirt_size = models.IntegerField(choices=SHIRT_SIZES)
Now the name MEDIUM is attached to your model and model instances:
>>> john = Person(name="John", shirt_size=2)
>>> john.shirt_size
2
>>> john.MEDIUM
2
If given a string, you can use getattr:
def get_shirt_size(instance, shirt_size):
return getattr(instance, shirt_size.upper())
choices_dict = {y: x for x, y in shirt_size.choices}
will give you a dictionary with all the ints as values and sizes as keys.
So you can write a function that returns the int of whatever shirt size you put in, or make choices_dict part of your Person object.
Related
I have a Item model with a numeric number field. This number field defaults to null.
# models.py
class Item(models.Model):
number = models.IntegerField(default=None, blank=True, null=True)
I want to set-up filters that can return a queryset of Items where number is in range - which is straightforward enough:
# filters.py
class ItemFilter(django_filters.FilterSet):
min_num = django_filters.NumberFilter(method="min_num_filter")
max_num = django_filters.NumberFilter(method="max_num_filter")
class Meta:
model = Item
fields = ("min_num", "max_num", "incl_null")
def min_num_filter(self, queryset, name, value):
return queryset.filter(number__gte=value)
def max_num_filter(self, queryset, name, value):
return queryset.filter(number__lte=value)
But what if I want to have an additional Boolean filter that can include Items that has null for number along with whatever Items matches the min_num and max_num range?
So for example, a URL query in the form of ?min_num=1&max_num=10&incl_null=True should return all Items where number is between 1 and 10 OR number is equal to None.
The following code does not work:
class ItemFilter(django_filters.FilterSet):
...
incl_null = django_filters.BooleanFilter(method="incl_null_filter")
class Meta:
model = Item
fields = ("min_num", "max_num", "incl_null")
// doesn't work
class incl_null_filter(self, queryset, name, value):
if value is True:
return queryset | Item.objects.filter(number=None)
if value is False:
return queryset
Edit: I've tried the methods in the "Filtering by empty values" documentation but I think that's for null values exclusively - where I'm looking for a range match OR a null value.
Try this query:
from django.db.models import Q
min_ = 0
max_ = 10
Item.objects.filter(Q(number__gte=min_, number__lte=max_) | Q(number__isnull=True))
Well, the only solution I can think of is to pass the min range, max range, and is_null boolean into a single char field then convert it into the 3 individual filters for actioning.
So the query URL will look like ?master_num=1-10-1 for range 1 - 10 incl. None and ?master_num=1-10-0 for range 1 - 10 excl. None.
class ItemFilter(django_filters.FilterSet):
master_num = django_filters.CharFilter(method="master_num_filter")
class Meta:
model = Item
fields = ("master_num")
def master_num_filter(self, queryset, name, value):
# array = [min, max, 1 or 0 for True and False]
array = value.split("-")
min = Q(year_published__gte=int(array[0]))
max = Q(year_published__lte=int(array[1]))
if array[2] == "1":
incl_null = Q(year_published=None)
return queryset.filter((min & max) | incl_null)
else:
return queryset.filter(min & max)
Would like to know if there's a better way to do this.
I am creating a Django factory for a model that contains a MultiPolygonField. It is throwing an error when I run the test. Detail below.
I have created a special provider to fake this field. The code is taken from the Django docs:
from django.contrib.gis.geos import (
Polygon,
MultiPolygon,
)
import factory
from faker import Faker
from faker.providers import BaseProvider
fake = Faker()
class Provider(BaseProvider):
def mpoly(self):
p1 = Polygon( ((0, 0), (0, 1), (1, 1), (0, 0)) )
p2 = Polygon( ((1, 1), (1, 2), (2, 2), (1, 1)) )
mpoly = MultiPolygon(p1, p2)
return mpoly
fake.add_provider(Provider)
class GeographyFactory(factory.DjangoModelFactory):
"""
A Factory to generate mock GeographyFactory objects to be used
in tests.
"""
class Meta:
model = 'location.Geography'
name = factory.Faker('name')
mpoly = fake.mpoly
The error I get when I run the tests, however, has stumped me.
TypeError: Cannot set Geography SpatialProxy (MULTIPOLYGON) with value of type: <class 'method'>
It seems to suggest that I am not returning the right type, but I can't figure out what it wants instead of the MultiPolygon object I am returning.
Why does it think I am returning <class 'method'>?
Any suggestions would be most welcome!
I would suggest defining a custom fuzzy attribute, which would allow some randomness in your tests.
import factory
import factory.fuzzy
from factory import random
class FuzzyPolygon(factory.fuzzy.BaseFuzzyAttribute):
"""Yields random polygon"""
def __init__(self, length=None, **kwargs):
if length is None:
length = random.randgen.randrange(3, 20, 1)
if length < 3:
raise Exception("Polygon needs to be 3 or greater in length.")
self.length = length
super().__init__(**kwargs)
def get_random_coords(self):
return (
factory.Faker("latitude").generate({}),
factory.Faker("longitude").generate({}),
)
def fuzz(self):
prefix = suffix = self.get_random_coords()
coords = [self.get_random_coords() for __ in range(self.length - 1)]
return Polygon([prefix] + coords + [suffix])
class FuzzyMultiPolygon(factory.fuzzy.BaseFuzzyAttribute):
"""Yields random multipolygon"""
def __init__(self, length=None, **kwargs):
if length is None:
length = random.randgen.randrange(2, 20, 1)
if length < 2:
raise Exception("MultiPolygon needs to be 2 or greater in length.")
self.length = length
super().__init__(**kwargs)
def fuzz(self):
polygons = [FuzzyPolygon().fuzz() for __ in range(self.length)]
return MultiPolygon(*polygons)
Then you can use these in your DjangoModelfactory;
class GeographyFactory(factory.DjangoModelFactory):
"""
A Factory to generate mock GeographyFactory objects to be used
in tests.
"""
class Meta:
model = 'location.Geography'
name = factory.Faker('name')
mpoly = FuzzyMultiPolygon()
I have a few transformations I need to perform on my table before I aggregate.
I need to multiply transaction_type (which is either 1 or -1) by amount to yield a signed_amount. Then I need to sum all signed_amounts by primary_category (which is a foreign key to secondary category which is a foreign key of my table).
DEBIT = -1
CREDIT = 1
TRANSACTION_TYPE_CHOICES = (
(DEBIT, 'debit'),
(CREDIT, 'credit'),
)
class Transaction(models.Model):
amount = models.DecimalField(max_digits=7, decimal_places=2)
transaction_type = models.IntegerField(choices=TRANSACTION_TYPE_CHOICES)
secondary_category = models.ForeignKey(Secondary_Category)
class Primary_Category(models.Model):
name = models.CharField("Category Name", max_length=30)
category = models.ForeignKey(Primary_Category_Bucket)
class Secondary_Category(models.Model):
name = models.CharField("Category Name", max_length=30)
primary_category = models.ForeignKey(Primary_Category)
I'm stuck on the first bit though.
from django.db.models import Sum, Count, F
original_transactions = Transaction.objects.all()
original_transactions.signed_amount = F('transaction_type') * F('amount')
for transaction in original_transactions:
print transaction.signed_amount
When I try to sanity check that signed_amount is being calculated, I get an error that 'Transaction' object has no attribute 'signed_amount'. I don't want to save signed_amount to the database. I just want to generate it as derived field so I can calculate my totals.
How do I calculate this derived field and subsequently aggregate by primary_category.name?
User python decorator property on a method for class Transaction:
class Transaction(models.Model):
amount = models.DecimalField(max_digits=7, decimal_places=2)
transaction_type = models.IntegerField(choices=TRANSACTION_TYPE_CHOICES)
secondary_category = models.ForeignKey(Secondary_Category)
#property
def signed_amount(self):
return self.amount * self.transaction_type
Then for each Transaction object you can do transaction.signed_amount.
I'm not sure if the aggregation part could be done using queries, but if you don't have that many PrimaryCategory, then python would be good enough to achieve it.
Or you can do this.
all_transactions = Transaction.objects.all().order_by('secondary_category__primary_category_id')
sum = 0
if all_transactions:
primary_category_id = all_transactions[0].secondary_category.primary_category_id
for transaction in all_transactions:
if primary_category_id == transaction.secondary_category.primary_category_id:
sum += (transaction.amount * transaction_type)
else:
sum = (transaction.amount * transaction_type)
print sum
I have 3 models in django:
class Movie(models.Model):
mid = models.IntegerField(primary_key = True)
name = models.CharField(max_length = 100)
class User(models.Model):
username = models.CharField(max_length=128, null=True)
uid = models.CharField(max_length=100)
movie = models.ManyToManyField(Movie, through = "Vote")
class Vote(models.Model):
movie = models.ForeignKey(Movie)
user = models.ForeignKey(User)
rating = models.IntegerField()
here rating = 0/1, 0 means dislike, 1 means like
i want to make some queries using filters:
find out all movies that a current user likes. For that i use this following 2 queries, but none of them work. In both cases it gives erroneous results
ans = Movie.objects.filter(vote__user = self).filter(vote__rating = 1)
ans = Movie.objects.filter(user__uid = self.uid).filter(vote__rating = 1)
I have a list of users in an array ids. I want to find out how many users from this list like a particular movie?
i tried this, but this is also incorrect:
ret = User.objects.filter(uid__in = ids).filter(vote__movie = mov).filter(vote__rating = 1)
can somebody please help me with these 2 queries?
I'd also suggest letting django assign the model's id's but if you are using a legacy database or for some other reason need to assign the id's you can query like so:
# uid is some uid
user = User.objects.get(uid=uid)
likes = Movie.objects.filter(vote__user=user, vote__rating=1)
or
likes = Movie.objects.filter(vote__user__uid=some_uid, vote__rating=1)
count of people in the list of users who like a specific movie:
>>> uids = ['1','2','3']
>>> # if mov is a Movie instance
>>> votes = Vote.objects.filter(user__uid__in=uids, movie=mov, rating=1)
>>> print votes.query
SELECT "so1_vote"."id", "so1_vote"."movie_id", "so1_vote"."user_id", "so1_vote"."rating" FROM "so1_vote" INNER JOIN "so1_user" ON ("so1_vote"."user_id" = "so1_user"."id") WHERE ("so1_user"."uid" IN (1, 2, 3) AND "so1_vote"."movie_id" = 1 AND "so1_vote"."rating" = 1 )
>>> # if mov is a mid for a movie
>>> # get movie instance by using Movie.objects.get(mid=mov)
>>> # or query:
>>> # votes = Vote.objects.filter(user__uid__in=uids, movie__mid=mov, rating=1)
>>> likes_count = votes.count()
>>> print likes_count
0
combined:
likes_count = Votes.objects.filter(user__uid__in=uids, movie=mov, rating=1).count()
I have the following model structure below:
class Master(models.Model):
name = models.CharField(max_length=50)
mounting_height = models.DecimalField(max_digits=10,decimal_places=2)
class MLog(models.Model):
date = models.DateField(db_index=True)
time = models.TimeField(db_index=True)
sensor_reading = models.IntegerField()
m_master = models.ForeignKey(Master)
The goal is to produce a queryset that returns all the fields from MLog plus a calculated field (item_height) based on the related data in Master
using Django's raw sql:
querySet = MLog.objects.raw('''
SELECT a.id,
date,
time,
sensor_reading,
mounting_height,
(sensor_reading - mounting_height) as item_height
FROM db_mlog a JOIN db_master b
ON a.m_master_id = b.id
''')
How do I code this using Django's ORM?
I can think of two ways to go about this without relying on raw(). The first is pretty much the same as what #tylerl suggested. Something like this:
class Master(models.Model):
name = models.CharField(max_length=50)
mounting_height = models.DecimalField(max_digits=10,decimal_places=2)
class MLog(models.Model):
date = models.DateField(db_index=True)
time = models.TimeField(db_index=True)
sensor_reading = models.IntegerField()
m_master = models.ForeignKey(Master)
def _get_item_height(self):
return self.sensor_reading - self.m_master.mounting_height
item_height = property(_get_item_height)
In this case I am defining a custom (derived) property for MLog called item_height. This property is calculated as the difference of the sensor_reading of an instance and the mounting_height of its related master instance. More on property here.
You can then do something like this:
In [4]: q = MLog.objects.all()
In [5]: q[0]
Out[5]: <MLog: 2010-09-11 8>
In [6]: q[0].item_height
Out[6]: Decimal('-2.00')
The second way to do this is to use the extra() method and have the database do the calculation for you.
In [14]: q = MLog.objects.select_related().extra(select =
{'item_height': 'sensor_reading - mounting_height'})
In [16]: q[0]
Out[16]: <MLog: 2010-09-11 8>
In [17]: q[0].item_height
Out[17]: Decimal('-2.00')
You'll note the use of select_related(). Without this the Master table will not be joined with the query and you will get an error.
I always do the calculations in the app rather than in the DB.
class Thing(models.Model):
foo = models.IntegerField()
bar = models.IntegerField()
#Property
def diff():
def fget(self):
return self.foo - self.bar
def fset(self,value):
self.bar = self.foo - value
Then you can manipulate it just as you would any other field, and it does whatever you defined with the underlying data. For example:
obj = Thing.objects.all()[0]
print(obj.diff) # prints .foo - .bar
obj.diff = 4 # sets .bar to .foo - 4
Property, by the way, is just a standard property decorator, in this case coded as follows (I don't remember where it came from):
def Property(function):
keys = 'fget', 'fset', 'fdel'
func_locals = {'doc':function.__doc__}
def probeFunc(frame, event, arg):
if event == 'return':
locals = frame.f_locals
func_locals.update(dict((k,locals.get(k)) for k in keys))
sys.settrace(None)
return probeFunc
sys.settrace(probeFunc)
function()
return property(**func_locals)