Home > other >  Need help in returning the Date field in Django models
Need help in returning the Date field in Django models

Time:02-03

models.py

class Add_Timelog(models.Model):
    
    project=models.ForeignKey(Project,on_delete=CASCADE,related_name='project')
    project=models.ManyToManyField(Project)
    client=models.ForeignKey(Client,on_delete=CASCADE,related_name='client')
    client=models.ManyToManyField(Client)
    Job=models.ForeignKey(Add_Job,on_delete=CASCADE,related_name='Job')
    Job=models.ManyToManyField(Add_Job)
    Date = models.DateTimeField(max_length=10)
    Hours=models.TimeField(null=True)
    
    
    def __str__(self):
        return self.Date

TypeError at /api/Add_Timelog/ str returned non-string (type int) Request Method: GET Request URL: http://127.0.0.1:8000/api/Add_Timelog/ Django Version: 2.2.12 Exception Type: TypeError Exception Value:
str returned non-string (type int)

This is the error I received. The solution what I was expecting is to receive the date inputted by me in the database and receive the value as date (integer) not a string

CodePudding user response:

__str__ must return string and you are returning DateTimeField value. Convert that value to string in your Add_Timelog model as

def __str__(self):
    return str(self.Date)

More details on str[Django-doc]

CodePudding user response:

I understand the problem according to your question

first thing str() returns always string so typecast your date into string then it will work.

def __str__(self):
    return str(self.Date)

And this is not working because of your model making, as you cannot use both foregin key and manytomanyfield

Without your model if you create simple model so it is working see this:

class Add_Timelog(models.Model):
name = models.CharField(max_length=200)
hours = models.TimeField(null=True)
Date = models.DateTimeField(max_length=10)

def __str__(self):
    return str(self.Date)

It returns date and time simultaneously by converting it into string in admin panel

  •  Tags:  
  • Related