我有一个应用程序,我在报价模型中创建了报价和承包商之间的关系:
contractor = models.ForeignKey(Contractor, on_delete=models.CASCADE)
除了一件事,一切都很好。当我尝试使用详细名称搜索承包商模型时,我收到一个归因错误: "ManyToOneRel"对象没有属性"verbose_name">
搜索下面的代码(承包商/视图.py(:
def get(self,request):
contractors = self.model.objects.all()
if 'search' in request.GET:
search_for = request.GET['search']
if search_for is not '':
filter = request.GET['filterSelect']
search_in = [field.name for field in Contractor._meta.get_fields() if field.verbose_name==filter]
kwargs = {'{0}__{1}'.format(search_in[0], 'contains'): search_for}
contractors = self.model.objects.all().filter(**kwargs)
如果对构造函数模型执行搜索并且构造函数模型没有与报价模型相关的字段,为什么会收到错误? 我该如何解决这个问题?或者如何创建搜索栏,用户可以在其中选择从包含模型字段所有详细名称的下拉列表中搜索的位置?
承包商模式:
class Contractor(models.Model):
company_name = models.CharField("nazwa", max_length=200)
phone_number = models.CharField("telefon", max_length=50)
email = models.EmailField("e-mail")
website = models.CharField("www", max_length=100)
NIP = models.CharField("NIP", max_length=50)
REGON = models.CharField(max_length=50)
KRS = models.CharField(max_length=50)
city = models.CharField("miasto", max_length=100)
street = models.CharField(max_length=100)
postal_code = models.CharField(max_length=50)
notes = models.TextField()
def get_absolute_url(self):
return reverse('contractors:list', kwargs={'pk' : self.pk})
def __str__(self):
return self.company_name
因为您没有设置verbose_name
contractor = models.ForeignKey(Contractor, on_delete=models.CASCADE, verbose_name='Contractor Details')
但问题是你为什么要搜索verbose_name。列表理解search_in
应该做什么?