当前位置: 首页 > article >正文

Django外键模型未保存引用

在 Django 中使用外键关系时,如果遇到模型未保存引用的问题,通常是因为在创建或更新相关对象时,有关联对象未被正确保存或引用。这里提供一些常见的问题和解决方案来确保你的外键关系正确处理。

在这里插入图片描述

1、问题背景

在使用 Django 进行模型开发时,遇到一个问题,外键模型无法保存引用。具体来说,UserProfile 模型的外键引用 Customer 模型,在保存 UserProfile 模型时,引用关系丢失。

代码如下:

from django.db import models
from customers.models import Customer
from django.contrib.auth.models import User, Group
from django.contrib.sites.models import Site
from anfitrion.models import ModelBase
from django.db.models.signals import post_save

class UserProfile(ModelBase):
    user = models.OneToOneField(User)
    customer = models.ForeignKey(Customer)
    address = models.CharField(max_length = 255)
    phone_home = models.CharField(max_length = 16)
    phone_office = models.CharField(max_length = 16)
    expiration = models.DateTimeField(null=True, blank=True)
    picture = models.ImageField(upload_to='profiles/%Y/%m/%d')
    observations = models.TextField(null=True, blank=True)
    status = models.BooleanField()

    def __str__(self):
        return "%s's profile" % self.user  

def create_user_profile(sender, instance, created, **kwargs):
    if created:
        profile, created = UserProfile.objects.get_or_create(user=instance)  

post_save.connect(create_user_profile, sender=User)

class SiteProfile(ModelBase):
    site = models.OneToOneField(Site)

    def __str__(self):
        return "%s's profile" % self.user  

def create_site_profile(sender, instance, created, **kwargs):
    if created:
        profile, created = SiteProfile.objects.get_or_create(site=instance)  

post_save.connect(create_site_profile, sender=Site)

function running the saveing
def users_save (request):
    #try:
        if request.is_ajax() and request.POST:
            user_id = request.POST['user_id']
            s = get_current_site(request)
            u = User (
                      username = request.POST['username'],
                      first_name = request.POST['first_name'],
                      last_name = request.POST['last_name'],
                      email = request.POST['email']
                      )
            u.set_password(request.POST['password'])
            c = None
            if int( request.POST['customer_id'] ) > 0: 
                c = Customer.objects.get(id=request.POST['customer_id'])
            up = UserProfile(
                      customer = c,
                      address = request.POST['address'],
                      phone_home = request.POST['phone_home'],
                      phone_office = request.POST['phone_office']
                      )
            up.user = u
            u.save()
            if int( request.POST['group_id'] ) > 0:
                g = Group.objects.get( id = request.POST['group_id'] )
                g.user_set.add(u)
            return HttpResponse(1, mimetype='application/json')

2、解决方案

经过分析,发现问题出在保存模型的方式上。在代码中,先保存了用户模型 u,然后再将 u 设置为 UserProfile 模型的 user 属性,最后才保存 UserProfile 模型。这种方式会导致外键引用丢失,因为在保存 UserProfile 模型时,u 还没有被保存,因此引用关系无法建立。

正确的做法是先保存 UserProfile 模型,然后再保存用户模型 u。这样,外键引用就可以正常建立。

up = UserProfile(
                      customer = c,
                      address = request.POST['address'],
                      phone_home = request.POST['phone_home'],
                      phone_office = request.POST['phone_office']
                      )
up.save()
up.user = u
u.save()

修改后的代码如下:

from django.db import models
from customers.models import Customer
from django.contrib.auth.models import User, Group
from django.contrib.sites.models import Site
from anfitrion.models import ModelBase
from django.db.models.signals import post_save

class UserProfile(ModelBase):
    user = models.OneToOneField(User)
    customer = models.ForeignKey(Customer)
    address = models.CharField(max_length = 255)
    phone_home = models.CharField(max_length = 16)
    phone_office = models.CharField(max_length = 16)
    expiration = models.DateTimeField(null=True, blank=True)
    picture = models.ImageField(upload_to='profiles/%Y/%m/%d')
    observations = models.TextField(null=True, blank=True)
    status = models.BooleanField()

    def __str__(self):
        return "%s's profile" % self.user  

def create_user_profile(sender, instance, created, **kwargs):
    if created:
        profile, created = UserProfile.objects.get_or_create(user=instance)  

post_save.connect(create_user_profile, sender=User)

class SiteProfile(ModelBase):
    site = models.OneToOneField(Site)

    def __str__(self):
        return "%s's profile" % self.user  

def create_site_profile(sender, instance, created, **kwargs):
    if created:
        profile, created = SiteProfile.objects.get_or_create(site=instance)  

post_save.connect(create_site_profile, sender=Site)

function running the saveing
def users_save (request):
    #try:
        if request.is_ajax() and request.POST:
            user_id = request.POST['user_id']
            s = get_current_site(request)
            u = User (
                      username = request.POST['username'],
                      first_name = request.POST['first_name'],
                      last_name = request.POST['last_name'],
                      email = request.POST['email']
                      )
            u.set_password(request.POST['password'])
            c = None
            if int( request.POST['customer_id'] ) > 0: 
                c = Customer.objects.get(id=request.POST['customer_id'])
            up = UserProfile(
                      customer = c,
                      address = request.POST['address'],
                      phone_home = request.POST['phone_home'],
                      phone_office = request.POST['phone_office']
                      )
            up.save()
            up.user = u
            u.save()
            if int( request.POST['group_id'] ) > 0:
                g = Group.objects.get( id = request.POST['group_id'] )
                g.user_set.add(u)
            return HttpResponse(1, mimetype='application/json')

通过修改代码,成功解决了 Django 外键模型无法保存引用的问题。

通过注意这些常见问题和采取正确的操作步骤,可以确保 Django 中的外键关系被正确处理,避免数据一致性和完整性问题。


http://www.kler.cn/a/470833.html

相关文章:

  • Selenium 八大元素定位方法及场景扩展
  • 计算机网络 (29)网络地址转换NAT
  • 性能测试01|性能测试理论
  • 基于SpringBoot的斯诺克球馆预约购票管理系统
  • atrust异常导致ERR_NETWORK_CHANGED
  • VR+智慧消防一体化决策平台
  • JAVA上门洗车家政上门服务小程序H5源码上门洗车APP
  • Ubuntu下的小bug
  • 微信小程序获取图片使用session(下篇)
  • leetcode155.最小栈
  • python学opencv|读取图像(二十七)使用time()绘制弹球动画
  • 企业二要素如何用C#实现
  • Scala语言的数据库交互
  • STM32-笔记30-串口间的通信
  • python常见绘图及代码
  • 技术文档撰写之道:构建清晰准确的知识传递桥梁
  • 【Java设计模式-1】单例模式,Java世界的“独苗”
  • C++中decltype遇到引用类型时的隐藏陷阱
  • 算法解析-经典150(矩阵、哈希表)
  • Redis - 6 ( 9000 字 Redis 入门级教程 )
  • 【快速入门 LVGL】-- 1、STM32 工程移植 LVGL
  • 深入了解SCPI协议:半导体测试与仪器自动化的核心
  • C语言——字符函数和内存函数
  • pikachu靶场--目录遍历和敏感信息泄露
  • 概率基本概念 --- 离散型随机变量实例
  • NLP 中文拼写检测纠正论文-08-Combining ResNet and Transformer