比较Django中的2个日期字段

 2021-04-27 

compare 2 date field in django

有人能建议我关于如何在django-admin中比较两个日期字段的任何想法吗?
我是管理员,我想说的是,每当我更新日期字段的日期时,其他日期字段也必须更改(比第一个日期多30天),如果第二个日期字段更改了,我想仅在django中更改另一个字段管理页面!
在此先感谢

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
STATUS_CHOICES = (
    ('P', 'Paid'),
    ('U', 'UNPAID'),
)
class Users(models.Model):
    status              = models.CharField(max_length=1, choices=STATUS_CHOICES , default="U")
    updated             = models.DateTimeField(default=now)
    expiry              = models.DateTimeField(default=updated_plus_30_days())
    # updated_plus_30_days():
        # if updated ="12/8/2017" and expiry is equal to"12/09/2017" and then i changed
        # the updated field to be equal to"12/12/2017" then expiry have to equal to"12/1/2018"
        # if the updated field is >= than expiray then expiray have to increase one month and check
            # if status  is == p:
            #    status = u
            # else :
            #   status = u

您可以尝试这样的事情。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
from datetime import datetime

#pip install python-dateutil
from dateutil.relativedelta import relativedelta


class Users(models.Model):
    status              = models.CharField(max_length=1, choices=STATUS_CHOICES , default="U")
    updated             = models.DateTimeField(default=now)
    expiry              = models.DateTimeField()

    def save(self, *args, **kwargs):
        self.expiry = self.updated + relativedelta(days=30)
        super(Users, self).save(*args, **kwargs)

您好,您能检查一下吗

1
2
3
4
5
6
7
8
9
10
11
12
STATUS_CHOICES = (
('P', 'Paid'),
('U', 'UNPAID'),
)
from datetime import datetime, timedelta
class Users(models.Model):
    status              = models.CharField(max_length=1, choices=STATUS_CHOICES , default="U")
    updated             = models.DateTimeField(default=now)
    expiry              = models.DateTimeField()
    def save(self):
         self.expiry = default=self.updated+timedelta(days=30)
         super(Users, self).save()