I'm trying this:

retVal= ""
dI = models.DateField(date(year=2005, month=11, day=1))
dF = models.DateField(date(year=2005, month=11, day=6))

diff = dF - dI

retVal += diff + "message"

But I'm getting this error

unsupported operand type(s) for -: 'DateField' and 'DateField'

Can you help me please?

有帮助吗?

解决方案

You're doing something very odd. You have django model code, which defines Field objects which contain no value. Only instances contain field values (you're defining things on the class level) so whatever you're doing should be put in a class method.

Perhaps you're confused because django's metaclass magic converts references to those attributes to python values from the database?

class MyModel(models.Model):
    foo = models.DateField()

    print foo  # is a models.DateField

    def get_foo_after_django_magic(self):
        print self.foo  # is a datetime() instance

其他提示

DateFields are not the same as python datetime instances so you cannot do what you are trying to do because DateFields do not allow that operation. The answer Raunak provided is correct.

If you had a model that had DateField as an attribute in it you would then be to do something like.

my_object = MyModelWithDateField.object.get(pk=1)
diff = datetime.today - my_object.some_datefield

You can subtract the values for the Datefiedl i.e.

df = datetime.date(year=2005, month=11, day=1)
di = datetime.date(year=2005, month=11, day=6)

You can not directly perform the action on the datefield's

When you try to subtract two date object the diff's returns a timedelta instanace

>>> df = datetime.date(year=2005, month=11, day=1)
>>> di = datetime.date(year=2005, month=11, day=6)
>>> di -d5
datetime.timedelta(5)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top