basic filtering in django using queryset - django

model.py
class Venue(models.Model):
place = models.CharField(max_length=50)
venue_Name = models.CharField(max_length=100)
rent = models.IntegerField()
parking_area = models.IntegerField()
def __unicode__(self):
return self.venue_Name
i want to filter this model using places which is selected in a droupdown list in one page when press filter display the model values from the database. though i read django doc i didnt understand the process of filtering

This is the part in the documentation you should be looking at - https://docs.djangoproject.com/en/dev/topics/db/queries/#retrieving-specific-objects-with-filters
The query that filters model values from the database is:
Venue.objects.filter(place='<dropdown-select>')

Venue.objects.filter(place= a[0])
a[0] being the value received from drop-down list

Related

Django query - how to filter sum by date?

I am struggling with a queryset in a Django view. Basically, I have three models: User, ActivityLog, & ActivityCategory.
User is the built-in.
ActivityLog looks like this:
class ActivityLog(models.Model):
activity_datetime = models.DateTimeField(default=timezone.now)
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, related_name='activity_user')
activity_category = models.ForeignKey(ActivityCategory, on_delete=models.CASCADE, null=True, related_name='activity_cat')
activity_description = models.CharField(max_length=100, default="Misc Activity")
Activity Category:
class ActivityCategory(models.Model):
activity_name = models.CharField(max_length=40)
activity_description = models.CharField(max_length=150)
pts = models.IntegerField()
My goal is to return an aggregate by user of all the points they have accumulated by participating in activities in the log. Each log references an ActivityType, different types are worth different points.
I accomplished this with the following query in the view:
class UserScoresAPIView(generics.ListAPIView):
queryset = User.objects.all()
serializer_class = UserScoresSerializer
def get_queryset(self):
queryset = User.objects.annotate(total_pts=Coalesce(Sum('activity_user__activity_category__pts'), 0)).order_by('-total_pts')
return queryset
So now I need to add to this query and restrict it based on date of the activity. I want to basically add a filter:
.filter('activity_user__activity_datetime__gte=datetime.date(2020,10,1)')
How can I add this into my current query to accomplish this? I tried to do so here:
queryset = User.objects.annotate(total_pts=Coalesce(Sum('activity_user__activity_category__pts').filter('activity_user__activity_datetime__gte=datetime.date(2020,10,1)') , 0)).order_by('-total_pts')
But that would happen after the Sum and wouldn't be helpful (or work...) so I tried to chain it where it is pulling the User objects ​
User.objects.filter('activity_user__activity_datetime__gte=datetime.date(2020,10,1)').annotate(total_pts=Coalesce(Sum('activity_user__activity_category__pts'), 0)).order_by('-total_pts')
But now I am receiving an error when trying to parse my query:
ValueError: too many values to unpack (expected 2)
I am confused at where to go next and appreciate any guidance.
Thank you.
BCBB
Aaaaaaand I got so focused on how to chain these together that I thought I was doing it wrong but in reality, I am just not sure what possessed me to enclose the filter in quotes...
Arrrrg. It's working now as listed last without the quotes...
User.objects.filter(activity_user__activity_datetime__gte=datetime.date(2020,10,1)).annotate(total_pts=Coalesce(Sum('activity_user__activity_category__pts'), 0)).order_by('-total_pts')

Django two parameter filter query with foreign key

My Django models look like this:
class User(models.Model):
userid = models.CharField(max_length=26,unique=True)
#some more fields that are currently not relevant
class Followers(models.Model):
user = models.ForeignKey('User',related_name='usr')
coins = models.IntegerField()
followers = models.CharField(max_length=26, null=True, blank=True)
I would now like to make a filter query in my Followers table selecting every entry where users have ID x and followers have ID y (I expect to get one result from the query).
To visualize what I have tried and know won't work is this:
queryfilter = Followers.object.filter(followers=fid, user=uid)
and this:
queryfilter = Followers.object.filter(followers=fid, user__userid=uid)
In the end I would like to access the coins:
c = queryfilter.coins
It may be possible that I cannot do it with one single query and need two, since I am trying to do a filter query with two tables involved.
Firstly, I have modified your 'Followers' model (for naming convention).
models.py
class Follower(models.Model):
user = models.ForeignKey('User', related_name='followers')
coins = models.IntegerField()
key = models.CharField(max_length=26, null=True, blank=True)
Your queryset should be ..
views.py
#coins
coins = Follower.objects.filter(key=fid, user__userid=uid).get().coins

Django queryset filter model where related objects have ALL a field value

I have two models:
class Photo(models.Model):
# fields
class PhotoTags(models.Model):
photo = models.ForeignKey(Photo, related_name="tags")
tag_name = models.Charfield()
is_disabled = models.BooleanField(default=False)
What I'm trying to achieve is to get photos where tags are all with is_disabled = True.
Is it possible to achieve it with a query, or do I have to loop photos and for each one check all tags?
EDIT
I tried with
Photos.objects.filter(tags__is_disabled=True)
but it returns photos with at least one tag that is disabled
Thank you
Yo can use Photo.objects.filter(tags__is_disabled=True)

Django fetch all relations

I have an app with a similar structure as this snippet
class Blog(models.Model):
name = models.CharField(max_length=25)
class Category(models.Model):
name = models.CharField(max_length=25)
blog = models.ForeignKey(Blog)
class Entry(models.Model):
title = models.CharField(max_length=25)
category = models.ForeignKey(Category)
What is the most generic way, that i will be able to use in other apps to fetch all blogs with their category and entries?
I thought about creating a manager for the Blog model, that can fetch all the Categories for that blog, but it's hardcoding the model names
class BlogManager(models.Manager):
def categories(self):
return Category.objects.filter(blog=self)
Any suggestions?
What you want is a Select Related. It returns a QuerySet that will automatically "follow" foreign-key relationships, selecting that additional related-object data when it executes its query. Your query for Blogs would look something like:
Blog.objects.select_related().filter( something )
or
Blog.objects.select_related().get( something )
Why not use a standard way?
Filter using Blog's PK with FK relation.
Category.objects.filter(blog__pk=self.pk)

django - multiple queries into one

I want to find the Records with a certain tag within 100 mile radius. I have two queries that work independently (see below) but I don't know how to put them together.
Also Records model has a foreign key pointing to the GeoLocation model called geo_location. I want to be able to show fields from both models (Records and GeoLocation) in one shot. I tried with .select_related() on the GeoLocation query below but for some reason I only get it to show the GeoLocation model fields and not the additional Records model fields as I expected.
tag_search = Records.objects.filter(tags__slug__in=[tag])
geo_search = GeoLocation.objects.select_related().filter(srid2163__distance_lte=(pnt, D(mi=100))).distance(pnt)
Any ideas?
These are my models:
from taggit.managers import TaggableManager
from django.contrib.gis.db import models
class GeoLocation (models.Model):
lat = models.FloatField(blank=True)
long = models.FloatField(blank=True)
srid2163 = models.PointField(blank=True,srid=2163)
server_time = models.DateTimeField(auto_now_add=True)
objects = models.GeoManager()
def __unicode__(self):
return u'%s %s %s' % (self.lat, self.long, self.server_time)
class Records(models.Model):
title = models.CharField(blank=True, max_length=50)
message_body = models.TextField()
server_time = models.DateTimeField(auto_now_add=True)
geo_location = models.ForeignKey(GeoLocation, related_name='geoloc')
tags = TaggableManager()
def __unicode__(self):
return u'%s %s %s' % (self.title, self.message_body, self.server_time)
For the tags field in the Records model I'm using django-taggit.
There are two things wrong here.
Firstly, you've misunderstood what select_related() does. It doesn't bring the fields from the related model into the current one. Instead, it just pre-fetches the related instance, so that doing the model_instance.foreignkey_field.field_on_related_model doesn't cause another db hit.
Secondly, your models contradict what you originally said about the foreignkey. You said it was from GeoLocation to Records, but the model definitions show that is the other way round. select_related does not work in that direction - there is no way, given your current models, to query GeoLocation and get the related Records in one go. However, you can query Records and get the related GeoLocations.
(Thirdly, your answer to my comment about the use of the single-element in lookup is completely irrelevant. Use tags_slug=tag.)