我有两个模特:
class MonthSalary(models.Model):
month = models.DateField(null=True)
def __str__(self):
return str(self.month.year) + '/' + str(self.month.month)
class SalaryPerMonth(models.Model):
user = models.ForeignKey(User, null=True, on_delete=models.CASCADE)
salary_month = models.ForeignKey(MonthSalary, null=True, on_delete=models.CASCADE)
main_salary_per_month = models.PositiveIntegerField(default=0, null=True)
net_salary_per_month = models.PositiveIntegerField(default=0, null=True)
class Meta:
constraints = [
models.UniqueConstraint(fields=["user", "salary_month"], name="all_keys_unique_together")]
def __str__(self):
return str(self.user.employeedetail.empcode) + ' ' + str(self.net_salary_per_month) + ' USD' + str(
self.salary_month)在视图中,我可以使用以下方式查询所有用户的薪资:
user = request.user
salary_per_month = SalaryPerMonth.objects.filter(user=user)在MonthSalary模型中,我在筛选用户薪资时,添加了几个月\年份,顺序不是Ex "2022-2,2022-4,2022-1,2021-4“,方法是对日期”相关的salary_month字段“排序如下:
salary_per_month = SalaryPerMonth.objects.filter(user=user).order_by('salary_month')这不太合宜。
Q1 =如何按年过滤?Q2 =如何按月订货?
发布于 2022-07-02 18:25:13
这就是我问题的第一部分"Q2“按月订购的答案
我所做的就是添加Meta类:
class Meta:
class MonthSalary(models.Model):
month = models.DateField(null=True)
class Meta:
ordering = ['-month']
class SalaryPerMonth(models.Model):
user = models.ForeignKey(User, null=True, on_delete=models.CASCADE)
salary_month = models.ForeignKey(MonthSalary, null=True, on_delete=models.CASCADE)
main_salary_per_month = models.PositiveIntegerField(default=0, null=True)
net_salary_per_month = models.PositiveIntegerField(default=0, null=True)
class Meta:
ordering = ['-salary_month']https://stackoverflow.com/questions/72838860
复制相似问题