开发者

Creating Schema for Users with Friends without many to many relationship?

开发者 https://www.devze.com 2023-02-08 11:33 出处:网络
I\'m working on my first Django app and trying to create the models for it but am stuck on how to create what I think should be a simple model relationship.I want to create a model for a user, with ty

I'm working on my first Django app and trying to create the models for it but am stuck on how to create what I think should be a simple model relationship. I want to create a model for a user, with typical attributes like username, password(hash of course), date joined, etc. Then would like to be able to link this user to all of their friends/followers on the site. But where i'm stuck is how i setup that relationship since one user can have many friends, I can key off that primary key for the User table, but how do i create a model for the friends table that has the primary key for the user table serve two functions, one as the mapping to the user, and the mapping to the primary key for all of their friends?

 from django.db import models

class User(models.Model):
    username = models.CharField(max_length=50)
    password = models.CharField(max_length=200)
    dateJoi开发者_如何学Goned = models.DateField('date joined')

class Friends(models.Model):
    user = models.ForeignKey(User)


First, I would recommend you not create your own User model, instead use the one that comes built in Django. It takes care of all the fields that you're looking for.

Second, I would also create a "profile" model and store my friends in that. Have a look here on what profiles are: http://docs.djangoproject.com/en/1.2/topics/auth/#storing-additional-information-about-users

Third, in your profile model, I would add a field for friends exactly as it's shown here: http://docs.djangoproject.com/en/1.2/ref/models/fields/#django.db.models.ManyToManyField.symmetrical

You can then access friends for a user like user.get_profile().friends.all(). A bit verbose, but keeps things clean.


CREATE TABLE friends (user_id int, friend_id int)

Both columns reference the user ID. I don't know Django models, but guessing from your code, it'd look like:

class Friends(models.Model):
    user = models.ForeignKey(User)
    friend = models.ForeignKey(User)
0

精彩评论

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