【问题标题】:Django Generate List of Opposite ModelsDjango 生成对立模型列表
【发布时间】:2021-10-30 17:19:53
【问题描述】:

我正在尝试开发一个程序来确定哪些植物对其他植物有益和有害。我希望它能够遍历植物列表并比较并查看一种植物的 deters_insects_and_animals 物种是否与另一种植物的 pests 匹配,然后将其添加到 ally_deter_pests_for(self): 的列表中 我不确定该怎么做。

     class AnimalSpecies(models.Model):
            common_name = CharField(max_length = 200, null = True, blank = True)
            scientific_name = CharField(max_length = 200, null = True, blank = True)
        
            genus = Foreign

Key(Genus, null = True, blank = True, on_delete = models.CASCADE)
        class Meta:
            verbose_name = "Animal Species"
            verbose_name_plural = "Animal Species"
        def __str__(self):
            return self.common_name
    #___________________________________________________________________________________Begin Species_______________________________________________
    class PlantSpecies(models.Model):
        #________________________Name & Relationships________________________
        common_name = CharField(max_length = 200, null = True, blank = True)
        species_name = CharField(max_length = 200, null = True, blank = True)
        genus = ForeignKey(Genus, blank = True, null =True, on_delete = models.CASCADE)
        rotation_family = ForeignKey(RotationFamily, blank = True, null = True, on_delete = models.CASCADE)
    
        #________________________Growth & Environment________________________
        annual = BooleanField(null = True, blank = True)
        GROWTH_HABIT_LIST = [
            ("H", "Herb"),
            ("S", "Shrub"),
            ("T", "Tree"),
            ("U", "Succulent"),
            ("G", "Grass"),
            ("F", "Fern"),
            ("V", "Vine")
        ]
        growth_habit = CharField(max_length = 20, blank = True, null = True, choices = GROWTH_HABIT_LIST)
        pruning = TextField(max_length = 1000, null = True, blank = True)
        days_to_germinate = IntegerField(null = True, blank = True, default = 0)
        days_to_maturity = IntegerField(null = True, blank = True, default = 0)
        zone = IntegerField(null = True, blank = True, default = 0)
    
        SUN_REQUIREMENT_LIST = [
            ("FH", "Full Shade"),
            ("FHPH", "Full Shade-Partial Shade"),
            ("PHFS", "Partial Shade-Full Sun"),
            ("FS", "Full Sun")
        ]
        sun_requirement = CharField(max_length = 200, null = True, blank = True, choices = SUN_REQUIREMENT_LIST)
        WATER_REQUIREMENT_LIST = [
            ("M", "Mesic"),
        ]
        water_requirement = CharField(max_length = 20, null = True, blank = True, choices = WATER_REQUIREMENT_LIST)
    
    
        pollinator = ManyToManyField(AnimalSpecies, blank = True, related_name = "pollinators")
        beneficials = ManyToManyField(AnimalSpecies, blank = True, related_name = "beneficials")
        pests = ManyToManyField(AnimalSpecies, blank = True, related_name = "Pests")
    
        deters_insect_and_animals = ManyToManyField(AnimalSpecies, blank = True, related_name = "deters_AnimalSpecies")
        
        #________________________Spacing________________________
        number_per_square_foot = IntegerField(null = True, blank = True, default = 0)
        spacing_inches = FloatField(max_length = 200, null = True, blank = True, default = 0)
        spread_inches = FloatField(max_length = 200, null = True, blank = True, default = 0)
        height = IntegerField(null = True, blank = True, default = 0)
        #________________________Yield________________________
        expected_yield_pounds = FloatField(max_length = 200, blank = True, null = True, default = 0)
        expected_pound_per_fruit = FloatField(max_length = 200, blank = True, null = True, default = 0)
        #________________________Description________________________
        COLOR_CHOICES = [
            ("RE", "Red"),
            ("OR", "Orange"),
            ("YE", "Yellow"),
            ("LGR", "Light Green"),
            ("GR", "Green"),
            ("DGR", "Dark Green"),
            ("BL", "Blue"),
            ("PU", "Purple"),
            ("PI", "Pink"),
            ("WH", "White")
        ]
       
        
        foliage_color = CharField(max_length = 20, null = True, blank = True, choices = COLOR_CHOICES)
        flower_color = CharField(max_length = 20, null = True, blank = True, choices = COLOR_CHOICES)
        fruit_color = CharField(max_length = 20, null = True, blank = True, choices = COLOR_CHOICES)
    
        PARTS_CHOICES = [
            ("FLRW", "Fruit, Leaves, Roots, Flowers"),
            ("FLW", "Fruit, Leaves, Flowers"),
            ("FR", "Fruit, Roots, Flowers"),
            ("LR", "Leaves, Roots, Flowers"),
            ("LRW", "Leaves, Roots, Flowers"),
            ("FL", "Fruit, Leaves"),
            ("FR", "Fruit, Roots"),
            ("LR", "Leaves, Roots"),
            ("F", "Fruit"),
            ("L", "Leaves"),
            ("R", "Roots"),
            ("W", "Flowers"),
            ("O", "Other"),
            ("N", "None")
        ]
        edible_parts = CharField(max_length = 20, null = True, blank = True, choices = PARTS_CHOICES)
        toxic_parts = CharField(max_length = 20, null = True, blank = True, choices = PARTS_CHOICES)
        @property
        def improves_growth_and_flavor(self):
            return ManyToManyField(self, blank = True, related_name = "improves_growth")
        
        @property
        def improves_health_and_flavor(self):
            return ManyToManyField(self, blank = True, related_name = "improves_health")
        @property
        def impairs_health_and_growth(self):
            return ManyToManyField(self, blank = True, related_name = "impairs_health")
            
        @property
        def visual_name(self):
            return f"{self.rotation_family.visual_color}{self.common_name}"
        visual_name.fget.short_description = "Name"
        @property
        def scientific_name(self):
            return f"{self.genus.scientific_name} {self.species_name}"
        @property
        def expected_fruit_yield(self):
            try:
                return self.expected_yield_pounds / self.expected_pound_per_fruit
            except:
                return "0"
    
        @property
        def ally_deter_pest_for(self):
            x = []
            y = PlantSpecies.objects.filter(self.pests)
            for i in range(len(self.deters_insect_and_animals)):
                for h in range(len(y)):
                    if self.deters_insect_and_animals[i] == y[h]:
                        x.append(f"{y[h].common_name} | {self.deters_insect_and_animals[i]}")
                    else:
                        pass
            return x

例如,它会发现万寿菊可以阻止跳蚤甲虫,而西兰花会受到跳蚤甲虫的影响。因此,金盏花ally_deter_pest_for(self):would x.append(broccoli)

现在我收到一个错误

内部服务器错误:/admin/GardenApp/plantspecies/ 回溯(最近一次通话最后): 文件“C:\Users\deant\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\options.py”,第 575 行,在 get_field 返回 self.fields_map[field_name] KeyError: 'ally_deter_pest_for'

在处理上述异常的过程中,又发生了一个异常:

Traceback(最近一次调用最后一次): 文件“C:\Users\deant\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\admin\utils.py”,第 265 行,在 lookup_field f = _get_non_gfk_field(选择,名称) _get_non_gfk_field 中的文件“C:\Users\deant\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\admin\utils.py”,第 296 行 字段 = opts.get_field(名称) 文件“C:\Users\deant\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\options.py”,第 577 行,在 get_field raise FieldDoesNotExist("%s 没有名为 '%s' 的字段" % (self.object_name, field_name)) django.core.exceptions.FieldDoesNotExist:PlantSpecies 没有名为“ally_deter_pest_for”的字段

在处理上述异常的过程中,又发生了一个异常:

Traceback(最近一次调用最后一次):文件 "C:\Users\deant\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py", 第 47 行,在内部 response = get_response(request) 文件 "C:\Users\deant\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py", 第 202 行,在 _get_response 中 response = response.render() 文件 "C:\Users\deant\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\response.py", 第 105 行,在渲染中 self.content = self.rendered_content 文件“C:\Users\deant\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\response.py”, 第 83 行,在 render_content 中 return template.render(context, self._request) File "C:\Users\deant\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\backends\django.py", 第 61 行,在渲染中 返回 self.template.render(context) 文件 "C:\Users\deant\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\base.py", 第 170 行,在渲染中 返回 self._render(context) 文件 "C:\Users\deant\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\base.py", 第 162 行,在 _render 中 返回 self.nodelist.render(context) 文件 "C:\Users\deant\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\base.py", 第 938 行,在渲染中 bit = node.render_annotated(context) 文件 "C:\Users\deant\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\base.py", 第 905 行,在 render_annotated 中 返回 self.render(context) 文件 "C:\Users\deant\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\loader_tags.py", 第 150 行,在渲染中 返回已编译的_parent._render(上下文)文件“C:\Users\deant\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\base.py”, 第 162 行,在 _render 中 返回 self.nodelist.render(context) 文件 "C:\Users\deant\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\base.py", 第 938 行,在渲染中 bit = node.render_annotated(context) 文件 "C:\Users\deant\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\base.py", 第 905 行,在 render_annotated 中 返回 self.render(context) 文件 "C:\Users\deant\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\loader_tags.py", 第 150 行,在渲染中 返回已编译的_parent._render(上下文)文件“C:\Users\deant\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\base.py”, 第 162 行,在 _render 中 返回 self.nodelist.render(context) 文件 "C:\Users\deant\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\base.py", 第 938 行,在渲染中 bit = node.render_annotated(context) 文件 "C:\Users\deant\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\base.py", 第 905 行,在 render_annotated 中 返回 self.render(context) 文件 "C:\Users\deant\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\loader_tags.py", 第 62 行,在渲染中 结果 = block.nodelist.render(context) 文件 "C:\Users\deant\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\base.py", 第 938 行,在渲染中 bit = node.render_annotated(context) 文件 "C:\Users\deant\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\base.py", 第 905 行,在 render_annotated 中 返回 self.render(context) 文件 "C:\Users\deant\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\loader_tags.py", 第 62 行,在渲染中 结果 = block.nodelist.render(context) 文件 "C:\Users\deant\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\base.py", 第 938 行,在渲染中 bit = node.render_annotated(context) 文件 "C:\Users\deant\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\base.py", 第 905 行,在 render_annotated 中 返回 self.render(context) 文件 "C:\Users\deant\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\admin\templatetags\base.py", 第 33 行,在渲染中 返回 super().render(context) 文件 "C:\Users\deant\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\library.py", 第 214 行,在渲染中 _dict = self.func(*resolved_args, **resolved_kwargs) 文件“C:\Users\deant\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\admin\templatetags\admin_list.py” , 第 341 行,在 result_list 中 “结果”:列表(结果(cl)),文件“C:\Users\deant\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\admin\templatetags\admin_list.py”, 第 317 行,在结果中 yield ResultList(None, items_for_result(cl, res, None)) 文件 "C:\Users\deant\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\admin\templatetags\admin_list.py ", 第 308 行,在 init 中 super().init(*items) 文件“C:\Users\deant\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\admin\templatetags\admin_list .py", 第 233 行,在 items_for_result 中 f, attr, value = lookup_field(field_name, result, cl.model_admin) 文件 "C:\Users\deant\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\admin\utils.py", 第 276 行,在lookup_field 中 attr = getattr(obj, name) 文件 "C:\Users\deant\OneDrive\Documents\Django\Aegirsoft_Garden\GardenApp\models.py", 第 201 行,在 ally_deter_pest_for y = PlantSpecies.objects.filter(self.pests) 文件“C:\Users\deant\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\manager.py”, 第 85 行,在 manager_method 中 返回 getattr(self.get_queryset(), name)(*args, **kwargs) 文件 "C:\Users\deant\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\查询.py", 第 942 行,在过滤器中 return self._filter_or_exclude(False, *args, **kwargs) 文件 "C:\Users\deant\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\query.py", 第 962 行,在 _filter_or_exclude clone._filter_or_exclude_inplace(negate, *args, **kwargs) 文件 "C:\Users\deant\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\query.py", 第 969 行,在 _filter_or_exclude_inplace self._query.add_q(Q(*args, **kwargs)) 文件“C:\Users\deant\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\sql\query .py", 第 1358 行,在 add_q 子句,_ = self._add_q(q_object, self.used_aliases) 文件“C:\Users\deant\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\sql\query.py ", 第 1377 行,在 _add_q child_clause,need_inner = self.build_filter(文件“C:\Users\deant\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\sql\query.py”, 第 1255 行,在 build_filter arg,value = filter_expr TypeError:无法解压缩不可迭代的 ManyRelatedManager 对象 [01/Sep/2021 01:51:57] “GET /admin/GardenApp/plantspecies/HTTP/1.1" 500 400341

【问题讨论】:

  • 请将完整的错误回溯添加到您的问题中!

标签: python django


【解决方案1】:

你首先需要获取所有相关的对象。

for i in range(len(self.deters_insect_and_animals.all())):
    # further code

参考:ManyToMany Relationships

【讨论】:

  • range(len(…)) 是 Python 中最常见的反模式之一。
  • @KlausD。对于查询集,我同意。但是这个答案旨在解决问题中提到的错误。
  • 那你应该用真实的信息让它成为一个真实的答案。
  • 什么是反模式?
猜你喜欢
  • 2017-06-14
  • 2010-09-17
  • 2012-03-25
  • 1970-01-01
  • 2023-03-14
  • 2018-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多