[英]Foreign key not shown with Many to Many Relationship in Django?
我有兩個簡單的模型,如下所示:
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)
根據數據庫規則,創建橋實體(表)。 我想知道的是在插入數據時,我想使用session_id(外鍵)插入數據庫,以便以后可以檢索以供使用。 我怎樣才能做到這一點?
如果您嘗試將數據添加到ManyToMany Relationships,則必須使用through
選項定義聯接表。 在這里閱讀更多信息。
請注意,但是,您不應該保存會話ID-您要實現什么目標? 原因是用戶將不會總是具有相同的sessionID,並且與該會話關聯的數據(即request.session [*])可能會被刪除。
無論如何,一個例子看起來像這樣
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()
根據您對問題的了解,您可能需要參考文檔的外鍵部分。 https://docs.djangoproject.com/en/dev/ref/models/fields/
例如:制造商=模型。ForeignKey('制造商')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.