gpt4 book ai didi

python - 在 Django 模型中,外键字段如何知道与其他模型中的哪个字段匹配?

转载 作者:行者123 更新时间:2023-12-02 01:53:57 25 4
gpt4 key购买 nike

我理解外键的作用,但我无法理解为什么它在 Django 中起作用。

我的项目模型位于“app1/models.py”文件中。该模型有一个名为“owner”的外键,它链接到我的“app2/models.py”文件中的 Profile 模型。

如果我只将模型名称传递给“所有者”字段,项目模型中的“所有者”字段如何知道它应该链接到配置文件模型中的“用户”字段? 我觉得我应该在项目模型中传递 Profile.field 或类似的内容:

owner = models.ForeignKey(Profile.user, null=True, blank=True ... )

Dennis Ivy 教程中的完整模型代码:

class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True)
name = models.CharField(max_length=200, blank=True, null=True)
email = models.EmailField(max_length=500, blank=True, null=True)
username = models.CharField(max_length=200, blank=True, null=True)
location = models.CharField(max_length=200, blank=True, null=True)
short_intro = models.CharField(max_length=200, blank=True, null=True)
bio = models.TextField(blank=True, null=True)
profile_image = models.ImageField(
null=True, blank=True, upload_to='profiles/', default='profiles/user-default.png')
social_github = models.CharField(max_length=200, blank=True, null=True)
social_twitter = models.CharField(max_length=200, blank=True, null=True)
social_linkedin = models.CharField(max_length=200, blank=True, null=True)
social_youtube = models.CharField(max_length=200, blank=True, null=True)
social_website = models.CharField(max_length=200, blank=True, null=True)
created = models.DateTimeField(auto_now_add=True)
id = models.UUIDField(default=uuid.uuid4, unique=True,
primary_key=True, editable=False)

class Project(models.Model):
owner = models.ForeignKey(Profile, null=True, blank=True, on_delete=models.SET_NULL)
title = models.CharField(max_length=200) #null is default=False and is required
description = models.TextField(null=True, blank=True) #for a bigger field, allows null(for db)/blank(for Django get/post)
featured_image = models.ImageField(null=True, blank=True, default='default.jpg')
demo_link = models.CharField(max_length=2000)
source_link = models.CharField(max_length=2000, null=True, blank=True) #can be blank in db
tags = models.ManyToManyField('Tag', blank=True) #quotes will ref other class after this one
vote_total = models.IntegerField(default=0, null=True, blank=True)
vote_ratio = models.IntegerField(default=0, null=True, blank=True)
created = models.DateTimeField(auto_now_add=True) #generate when model instance is created
id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False)

最佳答案

外键字段与另一个模型中的另一个字段不匹配。它与模型本身匹配。假设您想将名为“victor”的配置文件分配给新的项目模型对象,它会像这样:

from app_name.model import Project, Profile

profile1=Profile.objects.filter(name='victor').first()
new_project=Project(title='project 1',demolink='demo link',owner=profile1)

在这里,我们将用户对象分配给项目的所有者属性,而不是字段。

Profile.User 字段不是必需的。如果您想创建一个 customUser,我建议您应该查找一下,否则您会给自己带来许多身份验证问题。您必须为其创建一个模型管理器,然后才能开始自定义。它应该看起来像这样:

from django.db import models
from django.contrib.auth.models import User, AbstractUser
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.base_user import BaseUserManager


class CustomUserManager(BaseUserManager):
"""
Custom user model manager where email is the unique identifiers
for authentication instead of usernames.
"""
def create_user(self, username, password, **extra_fields):
"""
Create and save a User with the given username and password.
"""
if not username:
raise ValueError(_('The Username must be set'))
user = self.model(username=username, **extra_fields)
user.set_password(password)
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_superuser', False)
extra_fields.setdefault('is_active', True)
user.save()
return user

def create_superuser(self, username, password, **extra_fields):
"""
Create and save a SuperUser with the given username and password.
"""
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_superuser', True)
extra_fields.setdefault('is_active', True)

if extra_fields.get('is_staff') is not True:
raise ValueError(_('Superuser must have is_staff=True.'))
if extra_fields.get('is_superuser') is not True:
raise ValueError(_('Superuser must have is_superuser=True.'))
return self.create_user(username, password, **extra_fields)

class Profile(AbstractUser):

objects = CustomUserManager()
name = models.CharField(max_length=200, blank=True, null=True)
email = models.EmailField(max_length=500, blank=True, null=True)
location = models.CharField(max_length=200, blank=True, null=True)
short_intro = models.CharField(max_length=200, blank=True, null=True)
bio = models.TextField(blank=True, null=True)
profile_image = models.ImageField(
null=True, blank=True, upload_to='profiles/', default='profiles/user-default.png')
social_github = models.CharField(max_length=200, blank=True, null=True)
social_twitter = models.CharField(max_length=200, blank=True, null=True)
social_linkedin = models.CharField(max_length=200, blank=True, null=True)
social_youtube = models.CharField(max_length=200, blank=True, null=True)
social_website = models.CharField(max_length=200, blank=True, null=True)
created = models.DateTimeField(auto_now_add=True)
id = models.UUIDField(default=uuid.uuid4, unique=True,
primary_key=True, editable=False)

关于python - 在 Django 模型中,外键字段如何知道与其他模型中的哪个字段匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69854199/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com