开发者

Django Foreign Key Relationship And Creation

I have the following: models.py

class User(models.Model):
    开发者_StackOverflowemail = models.EmailField(unique=True)
    passwd = models.CharField()
    sessionID = models.CharField()

class StudentProfile(models.Model):
    school = models.CharField()
    name = models.CharField()
    user = models.ForeignKey(User, unique=True)

I don't understand how to create Users and StudentProfiles in django and have them linked. Could somebody please provide some sample code for creating a User, then creating a StudentProfile that refers to the User. Could they also post sample access code, ie let's say I have an email, please show how I would lookup the User, and then access the accompanying Profile information. Could I write a method as part of the User model to do this?

inb4 Why aren't you using the Django User model? This is as much of a thought exercise as anything, I also want to roll my own because the Django stuff was much more than I needed. I prefer it sweet and simple.

Thanks!


As addition to zhyfer's answer – You can approach things even a bit more basic:

user = User()
user.email = 'anon@anon.com'
user.save()

profile = StudentProfile()
profile.school = 'MIT'
profile.user = user
profile.save()

To get the related items you can also use the related manager:

user.profile_set.all()[0] should return the related StudentProfile for the created user.

And therefore user.profile_set.all()[0].school should return MIT while profile.user.email returns anon@anon.com

This all is a bit more elaborated in this blog post: Doing things with Django models

And finally you could write the get_profile method of the user-model like this:

def get_profile(self):
    return self.profile_set.all()[0]


If you have the above models,you can access a profile given an email via:

profile = StudentProfile.objects.get(user__email = 'test@test.com')
school = profile.school

I think that if you want a method in the user model to do this you can basically do the same thing:

def get_profile(email):
    return StudentProfile.objects.get(user__email = 'test@test.com')

To Link:

u = User.objects.create(email="test@test.com", passwd="test", sessionId=1) 
StudentProfile.objects.create(school="test", name="student", user=u)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜