Django模型不与其他模型对象关联

whitzsjs  于 2023-10-21  发布在  Go
关注(0)|答案(1)|浏览(170)

我正在使用Django创建一个应用程序,其中我有一个需要与公司模型关联的员工模型。我能够正确地将User模型与Employee模型关联起来,但是在将Company对象与Employee对象关联起来时遇到了问题。
我的看法:

from django.shortcuts import render
from django.http import HttpResponse

from company.models import Company
from .models import Employee
from .forms import UserForm, CompanyForm
from django.contrib.auth.models import User
import random, string
from django.db import IntegrityError

def new(request):    
    # Initialize forms
    user_form = UserForm(request.POST or None)
    company_form = CompanyForm(request.POST or None)

    # Check if the request is a POST request
    if request.method == 'POST':
        # Check if both forms are valid
        if user_form.is_valid() and company_form.is_valid():
            email = user_form.cleaned_data['email']

            # Check if a user with this email already exists
            try:
                user = User.objects.get(email=email)
                user_created = False
            except User.DoesNotExist:
                user = User(username=email, email=email)
                random_password = User.objects.make_random_password()
                user.set_password(random_password)
                user.save()
                user_created = True

            # Save the company form data
            company = company_form.save()

            # Check if an Employee already exists for this user
            try:
                employee = Employee.objects.get(user=user)
                employee_created = False
            except Employee.DoesNotExist:
                employee = Employee(user=user, company=company)
                employee.save()
                employee_created = True

            # Return appropriate response based on what was created
            if user_created:
                return HttpResponse('User and Employee created with password: ' + random_password)
            elif employee_created:
                return HttpResponse('Employee created for existing user.')
            else:
                return HttpResponse('User with that username already exists. Please try again.')

    user_form = UserForm()
    company_form = CompanyForm()

    # Render the page with the forms
    return render(request, 'new_business.html', {'user_form': user_form, 'company_form': company_form})

我的员工模型:

from django.db import models
from company.models import Company
from django.contrib.auth.models import User
from varvocrm.models import BaseModel

# Create your models here.
class Employee(models.Model):    
    user = models.OneToOneField(User, on_delete=models.CASCADE, blank=True, null=True)
    first_name = models.CharField(max_length=50, blank=True)
    last_name = models.CharField(max_length=50, blank=True)
    address = models.CharField(max_length=50, blank=True)
    city = models.CharField(max_length=50, blank=True)
    state = models.CharField(max_length=50, blank=True)
    zip_code = models.CharField(max_length=50, blank=True)
    phone = models.CharField(max_length=50, blank=True)
    website = models.CharField(max_length=50, blank=True)
    company = models.ForeignKey(Company, on_delete=models.CASCADE, blank=True, null=True)
    active = models.BooleanField(default=True)
    
    @property
    def is_deleted(self):
        return self.deleted_at is not None
    
    @property
    def is_active(self):
        return self.active and not self.is_deleted
    
    def __str__(self):
        return self.user.username if self.user else ''

我的公司型号:

from django.db import models
from varvocrm.models import BaseModel

# Create your models here.
class Company(models.Model):
    
    countries = [
        ('Norway', 'Norway'),
        ('Sweden', 'Sweden'),
        ('Denmark', 'Denmark'),
    ]
    
    organization_number = models.CharField(max_length=50, unique=True)
    name = models.CharField(max_length=50, blank=True)
    address = models.CharField(max_length=50, blank=True)
    city = models.CharField(max_length=50, blank=True)
    state = models.CharField(max_length=50, blank=True)
    zip_code = models.CharField(max_length=50, blank=True)
    country = models.CharField(max_length=50, default='Norway', choices=countries)
    phone = models.CharField(max_length=50, blank=True)
    email = models.EmailField(max_length=50)
    website = models.CharField(max_length=50, blank=True)
    
    def __str__(self):
        return self.organization_number
    
class Settings(models.Model):
    company = models.OneToOneField(Company, on_delete=models.CASCADE, blank=True, null=True)
    logo = models.ImageField(upload_to='logo/', blank=True)
    currency = models.CharField(max_length=50, default='NOK')
    tax = models.IntegerField(default=25)
    option_accept_offers = models.BooleanField(default=True)
    option_price_include_tax = models.BooleanField(default=True)
    option_send_email = models.BooleanField(default=True)
    option_locked = models.BooleanField(default=False)
    option_locked_message = models.CharField(max_length=50, blank=True, default='Locked by admin, contact customer service for more information.')
    
    def __str__(self):
        return self.company.name if self.company else ''
xqkwcwgp

xqkwcwgp1#

您没有将公司与现有员工关联。这可能是故意的,但如果现有员工没有与公司联系,他们将在上面的例子中保持这种状态。我也会调整一下你创建员工的方式。
你可以这样做

# Save the company form data
            company = company_form.save()

            # Check if an Employee already exists for this user
            try:
                employee = Employee.objects.get(user=user)
                if employee.company != company:
                    employee.company = company
                    employee.save(update_fields=['company'])
                employee_created = False
            except Employee.DoesNotExist:
                employee = Employee.objects.create(user=user, company=company)
                employee_created = True

或者更简单;

employee, employee_created = Employee.objects.get_or_create(user=user)

if employee.company != company:
    employee.company = company
    employee.save(update_fields=['company'])

相关问题