Django Filter with AND - python

Am having a django query to filter trough a model and print out the condition that meets the search.
Here is the views
if user_search != '' and (start_date != '' and end_date != ''):
items = Order.objects.filter(
Q(client__email__iexact=user_search) , Q(created_on__range=(start_date, end_date))
)
print "items ", items
The django filter is to print email address the user searched for, that falls within the date range.
But the code am having also prints email that wasn't searched for but falls within the date range
Here is the model
class Order(models.Model):
client = models.ForeignKey(User, related_name = "order_user")
order_number = models.CharField(max_length = 12)null=True)
terms_and_conditions = models.BooleanField(default=False)
order_status = models.CharField(max_length = 20, choices = ORDER_STATUS, default = "new")
created_on = models.DateTimeField(auto_now_add = True)
edited_on = models.DateTimeField(auto_now_add = False)
def __unicode__(self):
return self.order_number

Use & for doing AND operations on Q objects.
if user_search != '' and (start_date != '' and end_date != ''):
items = Order.objects.filter(
Q(client__email__iexact=user_search) & Q(created_on__range=(start_date, end_date))
)
print "items ", items

Related

'django model' object is not subscriptable

I get this error when I try to do a query set on the Django model
'AppUser' object is not subscriptable
despite it is working normally in a print statement but the error only appears when I put it in an IF statement
here is my code :
def to_representation(self, instance):
data = super().to_representation(instance)
print("reached here") #print normaly
print(AppUser.objects.filter(mobile=instance['mobile']).exists()) #print normally (False)
if AppUser.objects.filter(mobile=instance['mobile']).exists(): # Raises an Exception
if instance.playerprofile_set.all().count() > 0:
player_profile = instance.playerprofile_set.all()[0]
data['player_profile'] = PlayerProfileSerializer(
player_profile).data
for item in Team.objects.all():
if player_profile in item.players.all():
data['team'] = TeamSerializer(item).data
if item.cap.id == player_profile.id:
data['team'] = TeamSerializer(item).data
# data["team"] = instance.
return data
UPDATE
And here is my AppUser class:
class AppUser(models.Model):
first_name = models.CharField(max_length=33)
last_name = models.CharField(max_length=33)
mobile = models.CharField(max_length=33)
email = models.EmailField(null=True, blank=True, max_length=33)
birthdate = models.DateField(null=True, blank=True)
password = models.CharField(max_length=33)
confirm_password = models.CharField(max_length=33)
image = models.FileField(upload_to="uploads", null=True, blank=True)
main_user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
generated_code = models.PositiveIntegerField(null=True, blank=True)
user_langauge = models.CharField(max_length=33, default="en")
dark_mode = models.BooleanField(default=False)
def __str__(self):
return str(self.mobile) + " " + str(self.first_name) + " " + str(self.last_name)
so calling AppUser.objects.filter() should return a queryset or empty query set, and when adding exists() should return a True or
Instead of count, use exists():
if AppUser.objects.filter(mobile=instance['mobile']).exists():
if instance.playerprofile_set.exists():
player_profile = instance.playerprofile_set.first()
Because it is very efficient in contrast to count() and runs a very small query.
To your original problem, it is not possible to guess what is wrong from the sample code, specially when print works, if not.
Update
I think the error should be with this code:
instance['mobile']
Here instance should be an object, so instance.mobile or data['mobile'] should work.
try this:
def to_representation(self, instance):
data = super().to_representation(instance)
print("reached here") #print normaly
print(AppUser.objects.filter(mobile=instance['mobile']).count() > 0) #print normally (False)
if AppUser:
AppUser.objects.filter(mobile=instance['mobile']).count() > 0
if instance.playerprofile_set.all().count() > 0:
player_profile = instance.playerprofile_set.all()[0]
data['player_profile'] = PlayerProfileSerializer(
player_profile).data
for item in Team.objects.all():
if player_profile in item.players.all():
data['team'] = TeamSerializer(item).data
if item.cap.id == player_profile.id:
data['team'] = TeamSerializer(item).data
# data["team"] = instance.
return data

Select a valid choice Django Filtered Drop Down Menu

Devs,
In my project I have a form that has a field that has a student name selection, it is a drop down field by the students that are currently enrolled in that particular class. It gets this information from table Section Enrollment than checks the master Student table. The filtering works out correctly, however when I submit my form, it says the student name is not a valid choice. My guess is because its submitting that student name and not a ID, I'm not 100% sure. Here is my models and view. I don't know how to fix this. Appreciate that help.
QUERY IN QUESTION:
getstudents = SectionEnrollment.objects.filter(section_id=classid).select_related().values_list('studentpsid_id__student_name', flat = True)
MODELS:
# Creation of Classrooms and Assigned Teachers
class SectionEnrollment(models.Model):
sectionenrollmentpsid = models.CharField(primary_key = True,max_length = 50, default = "")
section = models.ForeignKey(Section,on_delete = models.PROTECT, default = "" ,)
studentpsid = models.ForeignKey(Student,on_delete = models.PROTECT, default = "" ,)
entry_date = models.DateField(blank=True)
exit_date = models.DateField(blank=True)
dropped = models.BooleanField(default = False, blank = True)
class Meta:
verbose_name = "Student Section Enrollment"
def __str__(self):
return self.sectionenrollmentpsid
# Where Basic Student Data Is Stored
class Student(models.Model):
studentpsid= models.CharField(primary_key = True , default = "", max_length = 50, unique = True)
student_name = models.CharField(max_length = 50)
first_name = models.CharField(max_length = 50, default = "")
last_name = models.CharField(max_length = 50,default = "")
gender = models.CharField(max_length = 1,default = "")
student_grade = models.CharField(max_length = 2, default = "")
home_room = models.CharField(max_length = 5, default = "")
student_enrollment = models.CharField(max_length = 2, default = "")
school_number = models.CharField(max_length = 15, default = "")
email = models.EmailField(default = "")
projected_graduation_year = models.CharField(max_length = 4, default = "")
counseling_goal = models.TextField(max_length = 255)
win_username = models.CharField(max_length = 50)
win_password = models.CharField(max_length = 50)
offsite_laptop = models.BooleanField(default = False, blank = True)
image = models.ImageField(default ="default.png", upload_to ='student_pics')
VIEW:
#login_required
def Rapid_Fire(request, classid):
if request.method == "GET":
date = datetime.date.today()
class_name = Section.objects.filter(sectionpsid=classid)
getstudents = SectionEnrollment.objects.filter(section_id=classid).select_related().values_list('studentpsid_id__student_name', flat = True)
student_selection = getstudents.all().order_by('studentpsid__student_name')
my_class_id = request.session['my_class_id']
sectionpsid = Section.objects.get(sectionpsid = my_class_id)
form = Rapid_Fire_Form()
form.fields["student_name"].queryset = getstudents
form.fields["sectionpsid"].queryset = class_name
context = ({'form': form, 'my_class_id': my_class_id, 'sectionpsid':sectionpsid,})
return render(request, 'points/rapid_fire.html', context )
elif request.method == "POST":
date = datetime.date.today()
class_name = Section.objects.filter(sectionpsid=classid)
getstudents = SectionEnrollment.objects.filter(section_id=classid).select_related().values_list('studentpsid_id__student_name', flat = True)
student_selection = getstudents.all().order_by('studentpsid__student_name')
my_class_id = request.session['my_class_id']
sectionpsid = Section.objects.get(sectionpsid = my_class_id)
form = Rapid_Fire_Form(request.POST)
form.fields["student_name"].queryset = getstudents
form.fields["sectionpsid"].queryset = class_name
if form.is_valid():
# Records logged in user to table
obj = form.save(commit= False)
userid = request.user
obj.created_by = userid
obj.save()
it seems the problem is here:
getstudents = SectionEnrollment.objects.filter(section_id=classid).select_related().values_list('studentpsid_id__student_name', flat = True)
student_selection = getstudents.all().order_by('studentpsid__student_name')
the values_list('studentpsid_id__student_name', flat = True) is collecting the students name not their id. so the form field will be field by incorrect data I think.
and if I'm right the solution may be:
students_id = SectionEnrollment.objects.filter(section_id=classid).select_related().values_list('studentpsid__id', flat = True)
student_selection = Student.objects.filter(id__in=students_id).order_by('student_name')
or:
student_selection = Student.objects.filter(sectionenrollment_set__section_id=classid).order_by('student_name')

filtering in django with foriegn key references

I have a view that is taking in query params and searching for venues which meet that query param.
cuisine = self.request.query_params.getlist('cuisine', 0)
if cuisine != 0:
cuisinelist =[]
for cuisine in cuisinelist:
cuisinepk = get_object_or_404(Cuisine, name=cuisine)
cuisinepk = cuisinepk.pk
cuisinelist.append(cuisinepk)
print('this is the cuisine pk')
print(cuisinepk)
venuelist = venuelist.filter(Q(cuisine1__in=cuisinelist) | Q(cuisine2__in=cuisinelist))
But it is not working in fact I do not get any returned venues.
the cuisine1 and cuisine2 in a venue object look like this.
cuisine1 = models.ForeignKey(Cuisine, on_delete=models.DO_NOTHING, related_name='cuisine1', blank=True, null=True)
cuisine2 = models.ForeignKey(Cuisine, on_delete=models.DO_NOTHING, related_name='cuisine2', blank=True, null=True)
I use this method when I wanted to check relations within a room. I am wondering if I need to do the same? What is the correct method?
seatedcapacity = self.request.query_params.get('seatedcapacity',0)
if seatedcapacity != 0:
try:
seatedcapacity = int(seatedcapacity)
except ValueError:
return Response(status=status.HTTP_400_BAD_REQUEST)
rooms = Room.objects.filter(venue=OuterRef('pk'), seatedcapacity__gte=seatedcapacity)
venuelist = venuelist.annotate(hasseatedcapacity=Exists(rooms))
venuelist = venuelist.filter(Q(hasseatedcapacity=True) | Q(fullbuyoutseatedcapacity__gte=seatedcapacity))

how to select data between 2 dates using sql queries in django?

models.py
My models.py
class Custom_user_model(User):
daily_target = models.IntegerField()
monthly_target = models.IntegerField()
yearly_target = models.IntegerField()
weekly_target = models.IntegerField()
call_target = models.IntegerField()
email_target = models.IntegerField()
meeting_target = models.IntegerField()
added_under = models.IntegerField()
profile_pic = models.TextField()
doj = models.DateTimeField(default='')
location_id = models.IntegerField()
locked = models.BooleanField()
default_currency = models.IntegerField()
date_change_permission = models.BooleanField()
deal_back_log = models.BooleanField()
created_date=models.DateTimeField(auto_now_add=True)
role_id=models.IntegerField()
profile_pic = models.FileField(upload_to='.')
objects = UserManager()
//This custom_user model is the extension of django's default user model.
class Deal(models.Model):
a_choices = ((0,'yes'),(1,'no'))
approved = models.IntegerField(choices=a_choices,default=1)
user_id = models.IntegerField()
company_id = models.IntegerField()
contact_id = models.IntegerField()
deal_title=models.CharField(max_length=200)
deal_value = models.CharField(max_length=20)
currency_id = models.IntegerField()
process_id = models.IntegerField()
expected_close_date = models.DateField(default='')
closed_date = models.DateField()
deal_milestone=models.IntegerField()
created=models.DateTimeField(auto_now_add=True)
last_modified=models.DateTimeField(auto_now_add=True)
s_choices = ((0,'active'),(1,'won'),(2,'junk'),(3,'lost'))
status = models.IntegerField(choices=a_choices,default=0)
type = models.CharField(max_length=50, default='deal')
source = models.CharField(max_length=50,default='O')
class user_Roles(models.Model):
code = models.CharField(max_length=20)
description = models.CharField(max_length=30)
permitted_menus = models.CharField(max_length=200)
created = models.DateTimeField(auto_now_add=True)
Using user_roles model, I have assigned permission for accessing data to the newly created user based on his/her role. I want to get the created deals which are added by the users having role_id = 2 and deals created date between the specified dates .
### views.py
st_date, end_date = week_magic(date.today())
cur = connection.cursor()
cur.execute("select *, CONCAT(au.first_name,' ',au.last_name) as full_name from myapp_custom_user_model mu left join auth_user au on mu.user_ptr_id = au.id INNER JOIN myapp_user_roles ml on ml.id= 2 and ml.id = mu.role_id LEFT JOIN (SELECT user_id,SUM( deal_value ) AS cnt FROM myapp_deal where status = 1 and DATE_FORMAT(closed_date,'%Y-%m-%d') BETWEEN " '%s' " and " '%s' " GROUP BY user_id)d ON mu.user_ptr_id = d.user_id where mu.locked !=1 and mu.role_id = 2 order by COALESCE( d.cnt, 0 ) DESC",(st_date,end_date))
users = dictfetchall(cur)
cur.close()
While executing the query it shows unsupported format error. So I used one more % symbol in the same query as follows:
cur.execute("select *, CONCAT(au.first_name,' ',au.last_name) as full_name from myapp_custom_user_model mu left join auth_user au on mu.user_ptr_id = au.id INNER JOIN myapp_user_roles ml on ml.id= 2 and ml.id = mu.role_id LEFT JOIN (SELECT user_id,SUM( deal_value ) AS cnt FROM myapp_deal where status = 1 and DATE_FORMAT(closed_date,'%%Y-%%m-%%d') BETWEEN " '%s' " and " '%s' " GROUP BY user_id)d ON mu.user_ptr_id = d.user_id where mu.locked !=1 and mu.role_id = 2 order by COALESCE( d.cnt, 0 ) DESC" %(st_date,end_date))
It doesn't give any error but the result is empty even though there is data because of this syntax: DATE_FORMAT(closed_date,'%%Y-%%m-%%d'). How to solve this?
First of all you should use ForeignKey fields for role_id in Custom_user_model and user_id in Deal. The same is probably true for some of the other _id fields in your models.
class Custom_user_model(User):
...
role = models.ForeignKey('Role')
...
class Deal(models.Model):
...
user = models.ForeignKey('Custom_user_model')
...
After that you can do your query like this:
# get deals from users with role_id=2
query = Deal.objects.filter(user__role_id=2)
# add filter for deals created by that user created between
start_date, end_date = week_magic(date.today())
query = query.filter(created__between=(start_date, end_date))

How can I add more items to an EmbeddedDocument with MongoEngine?

I'm trying to check if there is already an item with the current date and if not I will add it. the code below is not prompting any errors but it's not saving anything to MongoDB
if len(site.DaylyLog) != 0:
print len(site.DaylyLog)
print site.DaylyLog[-1]
current_date_daylylog = site.DaylyLog[-1]['aggregate_date']
else:
current_date_daylylog = ''
if current_date_daylylog == datetime.date.today():
#update document
print current_date_daylylog
print "calculating averages"
site.DaylyLog[-1].average_response_time = (site.DaylyLog[-1].average_response_time+record_uptime.response_time)/2
site.DaylyLog[-1].average_uptime = (site.DaylyLog[-1].average_uptime+100)/2
site.save()
else:
print current_date_daylylog
print "adding new uptime"
print site.url
aggregate_uptime = AggregatedUptime()
aggregate_uptime.average_response_time = record_uptime.response_time
aggregate_uptime.average_uptime = 100
aggregate_uptime.total_downtime = 0
aggregate_uptime.aggregate_date = datetime.date.today()
print aggregate_uptime.aggregate_date
print aggregate_uptime.average_response_time
site.DaylyLog.append(aggregate_uptime)
site.save()
print site.DaylyLog[-1].aggregate_date
As I mentioned in the comment above. The code I've posted was ok, but it was refencing something that i've changed in the model. It was just a newbie problem. :-)
The old model was
class Checkr(Document):
name = StringField()
slug = SlugField()
url = URLField()
frequency = IntField()
owner = IntField()
start_date = DateTimeField()
end_date = DateTimeField()
current_response_time = FloatField()
current_response_code = IntField()
hourly_log = ListField(EmbeddedDocumentField(AggregatedUptime))
dayly_log = ListField(EmbeddedDocumentField(AggregatedUptime))
weekly_log = ListField(EmbeddedDocumentField(AggregatedUptime))
When it should be
class Checkr(Document):
name = StringField()
slug = SlugField()
url = URLField()
frequency = IntField()
owner = IntField()
start_date = DateTimeField()
end_date = DateTimeField()
current_response_time = FloatField()
current_response_code = IntField()
HourlyLog = ListField(EmbeddedDocumentField(AggregatedUptime))
DaylyLog = ListField(EmbeddedDocumentField(AggregatedUptime))
WeeklyLog = ListField(EmbeddedDocumentField(AggregatedUptime))

Categories