I am just exploring how to get around with Django, and i created two models in my Django app.
from django.db import models
#first model
class Person(models.Model):
name = models.CharField(max_length=40)
email = models.CharField(max_length=100)
title = models.CharField(max_length=100)
image = models.CharField(max_length=200)
def __str__(self):
return self.name
#second model
class Skill(models.Model):
person = models.ForeignKey(Person)
skill = models.CharField(max_length=60)
years = models.CharField(max_length=40)
def __str__(self):
return self.skill, self.person
The first model is Person and the second model is Skill. Now how the relation goes is that each Person will have many skills.
Now I can update the database with the data, the admin section of the site also works fine.
On the Django Shell, I try to run the command:
Skill.object.all()
and what i get is the following error:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "C:Program Files (x86)Python36-32libsite-packagesdjangodbmodelsquery.py", line 235, in __repr__
return '<QuerySet %r>' % data
File "C:Program Files (x86)Python36-32libsite-packagesdjangodbmodelsbase.py", line 572, in __repr__
u = six.text_type(self)
TypeError: __str__ returned non-string (type tuple)
or if i try the command:
Skill.objects.get(pk=1)
i get:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "C:Program Files (x86)Python36-32libsite-packagesdjangodbmodelsbase.py", line 572, in __repr__
u = six.text_type(self)
TypeError: __str__ returned non-string (type tuple)
However if i run a command such as :
Skill.objects.get(skill='Photoshop').person.name
I get the name of the person who has the skill “Photoshop.”
I am trying to understand what I am doing wrong here; maybe I am not supposed to query a table with the foreign key this way? Or maybe I am doing something wrong.
Well, finally what I like to query is, I want to find all the skills of a Person with a given name or primary key.
2
Answers
__str__
should return astr
. So Change something like thisto
Your
__str__
method returns a tuple (self.skill, self.person), it must return those object’s str representation. In order to achieve that, change:to