Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Django returns a tuple instead of returning data

I have a simple model that is supposed to store some basic nutritional information about food, but whenever I create or edit the model it returns a tuple instead of the data. The app is simple and these are the only models I have in them.

Here is the model:

class User(AbstractUser):
    test_field = models.CharField(max_length=100)

    def __str__(self):
        return self.username


class Food(models.Model):
    name = models.CharField(max_length=100, null=False, blank=False),
    calories = models.IntegerField(default=0, null=False),
    protein = models.IntegerField(default=0),
    fat = models.IntegerField(default=0),
    rel_user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)

At first I thought it was an issue with how I was saving the model, so I tried creating one through the shell with the following commands:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

from api.models import User, Food
f = Food()
f.name = "Test"
f.calories = 1
f.rel_user = User.objects.get(id=1)
f.save()

If I call f.rel_user, it returns myemail@gmail.com, but if I call f.name, it returns (<django.db.models.fields.CharField>,).

In order to try to fix this, I’ve looked through the getting started project on https://docs.djangoproject.com/en/4.2/intro/tutorial01/, and have made sure that my settings.py, and my models are written like the ones on the site. I’ve tried using both the shell and a form to create test Food objects.

How can I fix this so when I try to get data from the food object it returns the actual value saved?

>Solution :

class Food(models.Model):
    name = models.CharField(max_length=100, null=False, blank=False),
    calories = models.IntegerField(default=0, null=False),
    protein = models.IntegerField(default=0),
    fat = models.IntegerField(default=0),

You’re getting tuples because you put a comma after these fields.

Remove the commas.

rel_user didn’t have a comma, so that field worked as expected.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading