簡體   English   中英

Django Model對象創建

[英]Django Model object creation

看一下我的Django模型(我只在其中粘貼一部分):

from django.contrib.auth.models import User as DjangoUser
from django.db import models

class Client(DjangoUser):
    address = models.ForeignKey(Address, blank=True, null=True)

我知道如何創建新的客戶和用戶:

client = Client(username=name, password=pass)
client.save()

此代碼創建兩個記錄:用戶和客戶端,客戶端使用其外鍵引用用戶。

在我的mysql數據庫中,已經有一個DjangoUser記錄。 現在,我想基於此現有用戶創建客戶端。 這個怎么做?

User是Django框架中的一種特殊情況。 您不應該使用繼承。

向其中添加數據的最佳實踐是創建一個模型並將其定義為用戶個人資料

為此創建一個模型:

from django.db import models
from django.contrib.auth.models import User

class UserProfile(models.Model):
    user = models.ForeignKey(User, unique=True) # ensure you create one profile only
    address = models.ForeignKey(Address, blank=True, null=True)

然后,您應該在設置中將其聲明為用戶個人資料:

AUTH_PROFILE_MODULE = "your_app.UserProfile"

然后在您看來:

def your_view(request):
    user_profile = request.user.get_profile()
    address = user_profile.address

這是執行此操作的標准方法,因為Django contrib應用程序(例如admin或auth(具有登錄名,權限等))將期望用戶是User類,而不是您正在創建的子類。

如果使用繼承,則request.user不會是您創建的對象,並且您將無法訪問其數據。

如果您關心的是能夠在同一頁面上編輯與用戶有關的所有數據,則可以采用以下方法

您可以這樣做:

from django.contrib.auth.models import User as DjangoUser
from django.db import models

class ClientDetails(models.Model):
   user = models.OneToOneField(DjangoUser)
   address = models.ForeignKey(Address, blank=True, null=True)

創建對象的代碼如下所示:

#assuming there is a user with this object already, you should add logic to handle the case when there is no user available.
django_user = DjangoUser.objects.get(username=name)

client = Client(user=django_user, password=pass)
client.save()

或者,如果您想擴展用戶,則可以執行以下操作,而這通常是不行的。 您應該為此使用配置文件。

from django.contrib.auth.models import User as DjangoUser
from django.db import models

class ClientDetails(DjangoUser):
   address = models.ForeignKey(Address, blank=True, null=True)

然后,您的客戶端代碼與您描述的沒有太大不同。

#assuming there is a user with this object already, you should add logic to handle the case when there is no user available.
client = Client(username=name, password=pass)
client.save()

用戶不是抽象的,所以像這樣擴展它是行不通的。 相反,您應該使用合成。

from django.contrib.auth.models import User as DjangoUser
from django.db import models

class ClientDetails(models.Model):
   user = models.OneToOneField(DjangoUser)
   address = models.ForeignKey(Address, blank=True, null=True)

此模式記錄在這里: http : //docs.djangoproject.com/en/dev/topics/auth/#storing-additional-information-about-users

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM