i have tried to apply filter datetime filed in django query,but i got result zero
class Customers(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30, null=True)
customer_code = models.CharField(max_length=30)
reference = models.CharField(max_length=30, null=True)
phone_office = models.CharField(max_length=250, null=True)
phone_residential = models.CharField(max_length=250, null=True)
contact_person_first_name = models.CharField(max_length=30)
mobile = models.BigIntegerField()
email = models.EmailField(null=True)
fax = models.CharField(max_length=15, null=True)
cr_limit = models.DecimalField(max_digits=10, decimal_places=2, null=True)
gstin = models.CharField(max_length=10, null=True)
state_code = models.CharField(max_length=10, null=True)
country = models.CharField(max_length=250, null=True)
opening_balance = models.DecimalField(max_digits=10, decimal_places=2, null=True)
opening_balance_date = models.DateTimeField(null=True)
payments_terms = models.ForeignKey(PaymentTerms, related_name='customer_terms', null=True, blank=True)
address_flag = models.BooleanField(default=False)
created_by = models.ForeignKey(SAUser, related_name='+')
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
the below code i have tried:
Customers.objects.filter(created_at__month=1).count()
but i have look at the query also
Customers.objects.filter(created_at__month=1).query
it seems like that
SELECT `customer_customers`.`id`, `customer_customers`.`first_name`, `customer_customers`.`last_name`, `customer_customers`.`customer_code`, `customer_customers`.`reference`, `customer_customers`.`phone_office`, `customer_customers`.`phone_residential`, `customer_customers`.`contact_person_first_name`, `customer_customers`.`mobile`, `customer_customers`.`email`, `customer_customers`.`fax`, `customer_customers`.`cr_limit`, `customer_customers`.`gstin`, `customer_customers`.`state_code`, `customer_customers`.`country`, `customer_customers`.`opening_balance`, `customer_customers`.`opening_balance_date`, `customer_customers`.`payments_terms_id`, `customer_customers`.`address_flag`, `customer_customers`.`created_by_id`, `customer_customers`.`created_at`, `customer_customers`.`updated_at` FROM `customer_customers` WHERE EXTRACT(MONTH FROM CONVERT_TZ(`customer_customers`.`created_at`, 'UTC', IST)) = 1
The manual query in mysql
select id,created_at from customer_customers;
+----+----------------------------+
| id | created_at |
+----+----------------------------+
| 1 | 2017-12-24 06:54:41.264756 |
| 2 | 2017-12-24 07:05:37.317395 |
| 3 | 2017-12-24 10:05:29.957158 |
| 4 | 2017-12-29 13:30:21.572926 |
| 5 | 2017-12-29 13:58:59.137774 |
| 6 | 2017-12-31 08:46:13.239080 |
| 7 | 2017-12-31 09:04:34.695830 |
| 8 | 2017-12-31 12:27:05.253016 |
| 9 | 2018-01-27 12:28:16.809840 |
| 10 | 2018-02-14 07:27:18.847884 |
| 11 | 2018-02-14 10:45:33.323448
Expected result should be 2
"When USE_TZ is True, datetime fields are converted to the current
time zone before filtering. This requires time zone definitions in the
database."
Add this to your settings file.
USE_TZ = False
Related
I have phone numbers stored as (921) 414-1313 in the database and I want to run a search lookup on that field, but I don't want to force them to include (, ' ', ) or -.
I'm using Postgres and tried to work with SearchVector initially, however it ran into the same challenge (so for now, I'm doing it the old fashioned way).
I have a model definition that returns an "unformatted" number as 9214141313, but I can't figure out how to query against my custom definition inside of the model?
Ultimately, I want a customer to be able to type in 921414 and get the response for the matching record.
GitHub:
https://github.com/varlenthegray/wcadmin/blob/dev/main/views.py#L25
Model:
class JobSite(models.Model):
customer = models.ForeignKey(Customer, on_delete=models.CASCADE)
quickbooks_id = models.IntegerField(editable=False, null=True, blank=True)
name = models.CharField(max_length=200, null=True, blank=True)
first_name = models.CharField(max_length=200, null=True, blank=True)
last_name = models.CharField(max_length=200, null=True, blank=True)
print_on_check_name = models.CharField(max_length=200, null=True, blank=True)
address = models.CharField(max_length=200, null=True, blank=True)
address_2 = models.CharField(max_length=200, null=True, blank=True)
city = models.CharField(max_length=100, null=True, blank=True)
state = models.CharField(max_length=50, null=True, blank=True)
zip = models.CharField(max_length=20, null=True, blank=True)
phone_number = models.CharField(max_length=30, null=True, blank=True)
email = models.CharField(max_length=400, null=True, blank=True)
service_interval = models.IntegerField(default=12)
next_service_date = models.DateField(null=True, blank=True)
primary_technician = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True)
active = models.BooleanField(default=True)
access_code = models.CharField(max_length=10, null=True, blank=True)
bill_parent = models.BooleanField(default=False)
requires_supporting_technician = models.BooleanField(default=False)
service_scheduled = models.BooleanField(default=False)
disable_service = models.BooleanField(default=False)
qb_created_on = models.DateTimeField(null=True, blank=True)
def __str__(self):
return f'{self.name}'
def phone_digits_only(self):
return re.sub("[^0-9]", "", self.phone_number)
#property
def is_past_due(self):
ignore_after = timezone.localdate() - relativedelta(years=5)
# noinspection StrFormat
if self.next_service_date:
if ignore_after >= self.next_service_date:
return False
else:
return timezone.localdate() > self.next_service_date
else:
return False
#property
def is_due_soon(self):
ignore_after = timezone.localdate() - relativedelta(years=3)
if self.next_service_date and self.next_service_date >= ignore_after:
three_months_future = timezone.localdate() + relativedelta(months=2)
return three_months_future > self.next_service_date
else:
return False
Views.py
def search_system(request, search_term=False):
if search_term:
job_sites = JobSite.objects.filter(
Q(first_name__icontains=search_term) |
Q(last_name__icontains=search_term) |
Q(quickbooks_id__icontains=search_term) |
Q(email__icontains=search_term) |
Q(phone_number_digits=search_term)
)
else:
job_sites = JobSite.objects.all().prefetch_related('customer')
data = []
for job in job_sites:
if job.first_name and job.last_name:
name = job.first_name + ' ' + job.last_name
elif job.customer.company:
name = job.customer.company
else:
name = job.customer.first_name + ' ' + job.customer.last_name
this_job = {'value': name}
data.append(this_job)
return JsonResponse(data, safe=False)
The best solution IMHO is to use the library phonenumbers which is very cleaned and well maintained.
Then do a custom "phone_cleaned" field where you add the signals "create" and "update" for this model, and update phone_cleaned accordingly (using the library to clean the phone number). And use that phone_cleaned to do all your searches.
I want to build an application in which a patient uploads his report to his companion doctor ,
So , I have two models one for Doctors and other for patients.
What I want is to have a relationship between the two models , in which a patient chooses his doctor from the registered doctors.
this is the code:
class DoctorModel(models.Model):
user = models.OneToOneField(CustomUser, on_delete=models.CASCADE)
doctorName = models.CharField(max_length = 150 , default="")
doctorEmail = models.EmailField(max_length=50, default="")
speciality = models.CharField(choices = SPECIALITY ,max_length = 20 , default="")
doctorStatus = models.CharField(choices = DOCTOR_STATUS ,max_length = 15 , default="")
class PatientModel(models.Model):
user = models.OneToOneField(CustomUser, on_delete=models.CASCADE)
patientName = models.CharField(max_length = 150 , default="", editable=True)
patientAge = models.IntegerField(default=0)
patientEmail = models.EmailField(max_length=50, default="", editable=True)
insuranceSyndicate = models.CharField(choices = INSURANCE_SYNDICATE, max_length = 15, default="")
slug = models.SlugField(max_length = 50 , default= '')
referencedDoctor = models.ForeignKey(DoctorModel, on_delete=models.Set_Null)
What I want that when a patient choose the "referencedDoctor" , he choose him from "doctorName" in the DoctorModel
How can I do it ?
you should create __ str __ method to your models.
class DoctorModel(models.Model):
user = models.OneToOneField(CustomUser, on_delete=models.CASCADE)
doctorName = models.CharField(max_length = 150 , default="")
doctorEmail = models.EmailField(max_length=50, default="")
speciality = models.CharField(choices = SPECIALITY ,max_length = 20 , default="")
doctorStatus = models.CharField(choices = DOCTOR_STATUS ,max_length = 15 , default="")
def __str__(self):
return f"{self.doctorName}"
BTW, try use null=True to your Fields. will be easier to implement.
You can define a dunder string function in the Doctor model like this
class DoctorModel(models.Model):
user = models.OneToOneField(CustomUser, on_delete=models.CASCADE)
doctorName = models.CharField(max_length = 150 , default="")
doctorEmail = models.EmailField(max_length=50, default="")
speciality = models.CharField(choices = SPECIALITY ,max_length = 20 , default="")
doctorStatus = models.CharField(choices = DOCTOR_STATUS ,max_length = 15 , default="")
def__str__(self):
return self.doctorName
I don't understand why i'm getting this error when I try to insert the xlsx file. This is my model
class Finance(models.Model):
invoiceNumber = models.CharField(blank=False, null=False,
primary_key=True)
student = models.CharField(max_length=50, blank=False, null=False)
rollGroup = models.CharField(max_length=50, blank=False, null=False)
invoiceTo = models.CharField(max_length=50, blank=False, null=False)
dob = models.CharField(max_length=50, null=True)
gender = models.CharField(max_length=50, blank=False, null=False)
status = models.CharField(max_length=50, blank=False, null=False)
schedule = models.CharField(max_length=50,blank=False, null=False)
totalValue = models.CharField(max_length=50, blank=False, null=False)
issueDate = models.CharField(max_length=50, null=True)
dueDate = models.CharField(max_length=50, null=True)
datePaid = models.CharField(max_length=50, null=True)
amountPaid = models.CharField(max_length=50, null=True)
def __str__(self):
return self.invoiceNumber
This is my resource model
class FinanceResource(resources.ModelResource):
invoiceNumber = Field(attribute='invoiceNumber', column_name='Invoice
Number')
student = Field(attribute='student', column_name='Student')
rollGroup = Field(attribute='rollGroup', column_name='Roll Group')
invoiceTo = Field(attribute='invoiceTo', column_name='Invoice To')
dob = Field(attribute='dob', column_name='DOB')
gender = Field(attribute='gender', column_name='Gender')
status = Field(attribute='status', column_name='Status')
schedule = Field(attribute='schedule', column_name='Schedule')
totalValue = Field(attribute='totalValue', column_name='Total
Value(PKR
₨)')
issueDate = Field(attribute='issueDate', column_name='Issue Date')
dueDate = Field(attribute='dueDate', column_name='Due Date')
datePaid = Field(attribute='datePaid', column_name='Date Paid')
amountPaid = Field(attribute='amountPaid', column_name='Amount Paid
(PKR
₨)')
class Meta:
model = Finance
import_id_fields = ('invoiceNumber',)
export_order = ('invoiceNumber', 'student', 'rollGroup',
'invoiceTo', 'dob', 'gender', 'status', 'schedule',
'totalValue', 'issueDate', 'dueDate', 'datePaid',
'amountPaid')
skip_unchanged = True
report_skipped = True
And the error im getting
And when i use the default primary key i get
Line number: 1 - str returned non-string (type int)
2, styles, harry, Spring 2020, Family, None, M, Pending, First Installment, 57000, None, 10/06/2020, None, 0
Traceback (most recent call last):
File "C:\Users\long play computers\PycharmProjects\DotsPrototype\venv\lib\site-packages\import_export\resources.py", line 559, in import_row
row_result.object_repr = force_str(instance)
File "C:\Users\long play computers\PycharmProjects\DotsPrototype\venv\lib\site-packages\django\utils\encoding.py", line 64, in force_str
s = str(s)
TypeError: str returned non-string (type int)
I want to filter my queryset if and only if loan exists in my model ShgGroupLoanMarking.
class ShgGroupLoanMarking(models.Model):
shg = models.ForeignKey(Shg, null=True)
category = models.CharField(max_length=25, choices=GROUP_CATEGORY, default="shg_group")
msss = models.ForeignKey(Msss, null=True)
shgmember = models.ForeignKey(ShgMember, null=True)
loan = models.ForeignKey(Loan, null=True)
date_of_marking = models.DateField(null=True)
paid = models.CharField(max_length=100, null=True)
loan_amount = models.CharField(max_length=100, null=True)
service_charge = models.CharField(max_length=100, null=True)
description = models.CharField(max_length=100, null=True)
status = models.CharField(max_length=100, null=True)
print_status = models.BooleanField(default=False)
sent_to_bank_status = models.BooleanField(default=False)
receipt_number = models.IntegerField(default=0)
How do I implement this?
ShgGroupLoanMarking.objects.filter(loan__isnull=False)
or
ShgGroupLoanMarking.objects.exclude(loan=None)
Here's my setup
Models
class League(models.Model):
league_name = models.CharField(max_length=60)
class Team(models.Model):
league = models.ForeignKey('League')
team_name = models.CharField(max_length=60)
class Game(models.Model):
league = models.ForeignKey('League')
teams = models.ManyToManyField(Team, through="GameTeams")
game_heading = models.CharField(max_length=40, null=True, blank=True)
class GameTeams(models.Model):
game = models.ForeignKey(Game)
team = models.ForeignKey(Team, null=True, blank=True)
How do I get all the (game, team) pairs associated with a particular league? This is what I tried:
league = League.objects.get(pk=1) #This obviously works
league.game_set.gameteams_set.all() #This doesn't work
The resultant set should be something something along these lines:
league_id | game_id | team_id
1 | 1 | 1
1 | 1 | 2
1 | 1 | 3
1 | 2 | 2
1 | 2 | NULL
you can do it like:
league = League.objects.get(pk=1)
gameteams = GameTeams.objects.filter(game__league=league, team__league=league)