我目前正在構建一個需要兩種不同用戶型別的 Django 應用程式,我知道跨多個模型/表存盤身份驗證資訊是一個壞主意。
因此,我創建了一個User模型來處理身份驗證資訊(用戶名、密碼等)。然后我創建了兩種不同的模型,一種用于買家,一種用于賣家,每個模型都有自己獨特的欄位和與用戶模型的一對一關系。
現在,我認為這會奏效,但問題是不同的買家和賣家仍有可能擁有相同的用戶關系。如何防止這種情況并將User模型限制為一個一對一的關系?
uj5u.com熱心網友回復:
您可以將該欄位添加到用戶模型而不是您的方式,這樣做可以確保一個用戶只能擁有一種型別
uj5u.com熱心網友回復:
您可以使用unique_together來實作您的目標,如下所示:
class Actor(models.Model):
"""An abstract base class for Buyer and Seller"""
# We define an id file in the abstract class
# this way the id is unique for Buyer and Seller
id = models.AutoField(primary_key=True)
class Meta:
abstract = True
class Buyer(Actor):
user_id = models.ForeignKey(User, ...)
class Meta:
unique_together = ('id', 'user_id',)
class Seller(Actor):
user_id = models.ForeignKey(User, ...)
class Meta:
unique_together = ('id', 'user_id',)
在此示例中,一位買家僅與一位用戶相關聯,一位賣家也僅與一位用戶相關聯。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/343302.html
標籤:Python 姜戈 django-models 外键 一对一
上一篇:在Django上處理選擇多個
