Defining class relations in django
I am new to Django/Python, so excuse me if my question is straightforwardly开发者_开发问答 obvious!
I am trying to create a User class, and each user will have the option to select (one or more) sports disciplines as his hobbies.
So far I defined all the sports activities in a class called Hobbies:
class Hobbies(models.Model):
sports_name = models.IntegerField()
and the user class:
class Profile(models.Model):
user = models.ForeignKey(User, unique=True)
gender = models.CharField(max_length=1,blank=True)
I have no idea how to proceed as I have no prior experience with django/Python.
I need to create a sort of array in my user class where I would store all the hobbies a certain user "registers" for.
Add a many-to-many field to your profile model, which enables you to create a relationship between users and hobbies:
class Profile(models.Model):
user = models.ForeignKey(User, unique=True)
gender = models.CharField(max_length=1, blank=True)
hobbies = models.ManyToManyField(Hobbies)
You can then get a list of a users hobbies by doing a related lookup:
user = Profile.objects.get(pk=1)
hobbies = user.hobbies.all()
More info: http://docs.djangoproject.com/en/dev/ref/models/fields/#manytomanyfield
Sounds like a M2M relation to me. Here is how to do this: http://docs.djangoproject.com/en/dev/topics/db/models/#many-to-many-relationships
Question indicates that you hadn't any experience with relational databases at all. As Django models maps (almost) directly to underlying db relations, I would suggest diving into some database (framework- and language-agnostic) tutorial//book.
For that, check this stackoverflow question. Then pick one of the RDBMS (PostgreSQL is fine, opensource, free) and experiment a little, then go back to Django.
精彩评论