Django related_name 具有 _set 功能

Django related_name with _set function

我在我的模型中使用了 related_name 标签,我正在尝试使用 _set 函数过滤我的表单。但是我遇到了这个错误;

  AttributeError: 'Client' object has no attribute 'contact_owner_set'

我认为问题就出在这里;

self.fields['contact_owner'].queryset = self.instance.client_owner.contact_owner_set.order_by('name') 

我已尝试删除 related_name 字段并将此位更改为;

self.fields['contact_owner'].queryset = self.instance.client_owner.contact_owner_set.order_by('name') 

但是我的其他功能需要 related_name。有什么办法可以解决这个问题吗?

models.py

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

class Client(models.Model):
    name = models.CharField(max_length=100)

    def get_absolute_url(self):
        return reverse("client-detailview", kwargs={"slug": self.slug}) 

    def __str__(self):
        return str(self.name)

class Contact(models.Model):
    client_owner = models.ForeignKey(Client,on_delete=models.CASCADE, related_name='contact_client') # client.contact_client
    name = models.CharField(max_length=100) 

    def get_absolute_url(self):
        return reverse("contact-detailview", kwargs={"slug": self.slug}) 

    def __str__(self):
        return str(self.client_owner) + " - " + str(self.name)

class Action(models.Model):
    client_owner = models.ForeignKey(Client,on_delete=models.CASCADE, related_name='action_client') # client.action_client
    contact_owner = models.ManyToManyField(Contact, related_name='action_contact', blank=True, null=True) # contact.action_contact
    topic = models.CharField(max_length=100, blank=True, null=True)

    def __str__(self):
        return str(self.topic) + " - " + str(self.user_owner) + " - " + str(self.client_owner) + " - " + str(list(self.contact_owner.all().values_list('name', flat=True)))

views.py

from django.shortcuts import render
from django.views.generic import ListView, CreateView, UpdateView
from django.urls import reverse_lazy

from .models import Action, Contact
from .forms import ActionForm

class ActionListView(ListView):
    model = Action
    context_object_name = 'actions'
    template_name = 'crm/action_list.html'

class ActionCreateView(CreateView):
    model = Action
    form_class = ActionForm
    template_name = 'crm/action_form.html' 
    success_url = reverse_lazy('action_changelist')

class ActionUpdateView(UpdateView):
    model = Action
    form_class = ActionForm
    template_name = 'crm/action_form.html'
    success_url = reverse_lazy('action_changelist')

forms.py

from django import forms
from .models import Action, Contact

class ActionForm(forms.ModelForm):
    class Meta:
        model = Action 
        fields = ('client_owner', 'contact_owner', 'topic') 
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs) 
        self.fields['contact_owner'].queryset = Contact.objects.none()

        if 'client_owner' in self.data:
            try:
                alan1 = int(self.data.get('client_owner'))
                self.fields['contact_owner'].queryset = Contact.objects.filter(client_owner_id = alan1)
            except (ValueError, TypeError):
                pass
        elif self.instance.pk and self.instance.client_owner: 
            print(self.instance.client_owner)
            print(type(self.instance.contact_owner))
            print(self.instance.contact_owner.values())
            self.fields['contact_owner'].queryset = self.instance.client_owner.contact_owner_set.order_by('name')

related_name 定义反向关系的名称,因此在您的情况下,没有具有关系 contact_owner_set.

的模型

例如,如果要访问客户联系人,则应使用client.contact_client属性;如果要获取联系人的操作,则必须使用 contact.action_contact 属性。

但是这里没有特别的关系contact_owner_set:

self.fields['contact_owner'].queryset = self.instance.client_owner.contact_owner_set.order_by('name') 

self.instance.client_ownerClient 实例并且 Client 实例没有属性 contact_owner_set.

而且您肯定必须使用复数重命名您的 related_name 以提高代码可读性。