简体   繁体   English

Django中没有显示多对多关系的外键?

[英]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. 我想知道的是在插入数据时,我想使用session_id(外键)插入数据库,以便以后可以检索以供使用。 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. 如果您尝试将数据添加到ManyToMany Relationships,则必须使用through选项定义联接表。 Read here for more information. 在这里阅读更多信息。

Note, however, you shouldn't be saving the session ID - what are you trying to achieve? 请注意,但是,您不应该保存会话ID-您要实现什么目标? 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. 原因是用户将不会总是具有相同的sessionID,并且与该会话关联的数据(即request.session [*])可能会被删除。

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/ https://docs.djangoproject.com/en/dev/ref/models/fields/

eg: manufacturer = models.ForeignKey('Manufacturer') 例如:制造商=模型。ForeignKey('制造商')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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