简体   繁体   中英

Foreign key not shown with Many to Many Relationship in Django?

I have a two simple models like this:

class User(models.Model):
    username = models.CharField(max_length=100) #Id is automatically generated by Django
    password = models.CharField(max_length=100)

    def __unicode__(self):
        return self.username

class File(models.Model):
    users = models.ManyToManyField(User)
    file_name = models.CharField(max_length=100)
    type = models.CharField(max_length=10)

With the rule of database, bridge entity(table) is created. What I want to know is while inserting the data I want to insert the database with the session_id(foreign key) in my case so that I can retrieve later for my use. How can I do that?

If your trying to add data to ManyToMany Relationships, you'll have to define the joining table using the through option. Read here for more information.

Note, however, you shouldn't be saving the session ID - what are you trying to achieve? The reason for this is a user won't always have the same sessionID and the data associated with the session (ie, request.session[*]) may be deleted.

In any case, an example would look something like this

class User(models.Model):
    username = models.CharField(max_length=100) #Id is automatically generated by Django
    password = models.CharField(max_length=100)

    def __unicode__(self):
        return self.username

class File(models.Model):
    users = models.ManyToManyField(User, through='UserFile')
    file_name = models.CharField(max_length=100)
    type = models.CharField(max_length=10)


class UserFile(models.Model):
    user = models.ForeignKey(User)
    file = models.ForeignKey(File)
    # Should probably use CharField if you know the length
    session_id = models.TextField()

From what I have understood from your question, you may want to refer Foreign Key Section of the documentation. https://docs.djangoproject.com/en/dev/ref/models/fields/

eg: manufacturer = models.ForeignKey('Manufacturer')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM