首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >“ManyToManyField”查询

“ManyToManyField”查询
EN

Stack Overflow用户
提问于 2017-03-22 16:32:45
回答 1查看 475关注 0票数 0

我在和我之前问过的web应用程序一起前进。

目前,我的models.py是

代码语言:javascript
复制
from django.db import models
from unittest.util import _MAX_LENGTH

class Alimento(models.Model):
    INTOLERANCIAS = (
        ('00', 'Ninguna'),
        ('GL', 'Gluten'),
        ('CR', 'Crustáceos'),
        ('HU', 'Huevos'),
        ('FS', 'Frutos Secos'),
        ('AP', 'Apio'),
        ('MO', 'Mostaza'),
        ('SE', 'Sésamo'),
        ('PE', 'Pescado'),
        ('CA', 'Cacahuetes'),
        ('SO', 'Sulfitos'),
        ('SJ', 'Soja'),
        ('LA', 'Lácteos'),
        ('AL', 'Altramuz'),
        ('ML', 'Moluscos'),
        ('CA', 'Cacao'),


    )
    nombre = models.CharField(max_length=60)
    intolerancia = models.CharField(max_length=2, choices=INTOLERANCIAS)

    def __str__(self):
        return self.nombre


class Receta(models.Model):
    nombre = models.CharField(max_length=100)
    raciones = models.IntegerField(default=1)
    preparacion = models.TextField(default='')
    consejos = models.TextField(blank=True)
    ingredientes = models.ManyToManyField(Alimento, through='Ingrediente', related_name='ingredientes')

    def __str__(self):
        return self.nombre

    def getIntolerancias(self):
        ing = self.ingredientes.all()
        intolerancias = []
        for i in ing:
            alimentos = i.alimento.all()
            for a in alimentos:
                intolerancias.append(a.get_intolerancia_display()) 

        return intolerancias



class Ingrediente(models.Model):
    receta = models.ForeignKey('recetas.Receta', on_delete=models.CASCADE)
    alimento = models.ManyToManyField(Alimento)
    cantidad = models.FloatField(default=0)
    descripcion = models.CharField(max_length=60, blank=True)

    def __str__(self):
        return self.alimento.__str__()

getIntolerancias方法应该列出与给定配方(Receta)的每一种成分相关的食物不耐受情况。为了做到这一点,我尝试用ing = self.ingredientes获取成分的查询集(Ingrediente),但是当我在shell上尝试时,我会得到以下错误消息

代码语言:javascript
复制
Traceback (most recent call last):   File "/usr/lib/python3.5/code.py", line 91, in runcode
    exec(code, self.locals)   File "<console>", line 1, in <module>   File "/usr/local/lib/python3.5/dist-packages/django/db/models/fields/related_descriptors.py", line 476, in __get__
    return self.related_manager_cls(instance)   File "/usr/local/lib/python3.5/dist-packages/django/db/models/fields/related_descriptors.py", line 758, in __init__
    self.target_field_name = rel.field.m2m_reverse_field_name()   File "/usr/local/lib/python3.5/dist-packages/django/utils/functional.py", line 15, in _curried
    return _curried_func(*(args + moreargs), **dict(kwargs, **morekwargs))   File "/usr/local/lib/python3.5/dist-packages/django/db/models/fields/related.py", line 1504, in _get_m2m_reverse_attr
    return getattr(self, cache_attr) AttributeError: 'ManyToManyField' object has no attribute '_m2m_reverse_name_cache'

我已经搜索了错误,但是答案 我发现似乎没有我所需要的东西(我可能只是不太明白它的存在吗?)

更新

当我在shell上运行这个时,我会这样做。

代码语言:javascript
复制
g = Receta.objects.get(nombre = 'Gazpacho')
g.getIntolerancias()

我犯了个错误

intolerancias.append(a.get_intolerancia_display()) AttributeError:“Ingrediente”对象没有属性“get_intolerancia_display”

但是,如果我迭代并获得g.ingredientes.all()的第一个元素并调用get_intolerancia_display(),它确实工作正常

代码语言:javascript
复制
a = g.ingredientes.all().first()
a.get_intolerancia_display()
'Gluten'
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-03-22 16:41:48

评论后的最新情况:

关于多到多关系的文档

代码语言:javascript
复制
def get_intolerancias(self):
        alimentos = self.ingredientes.all() # Give us all alimento of a recetta
        intolerancias = []
        for a in alimentos:
            intolerancias.append(a.get_intolerancia_display())            
        return intolerancias
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42957606

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档