ValueError:字段“ id”应为数字,但为“低语”

时间:2020-05-11 07:33:36

标签: django django-models django-rest-framework django-queryset

这是我的模特。py

  class RUDevice(models.Model):
        name = models.CharField(_("Device Name"), max_length=100, blank=False, null=False, help_text="Device Name", default='')
        last_active = models.DateTimeField(_("Last Active"), auto_now=False, auto_now_add=False, 

class Magazine(models.Model):
    device = models.ForeignKey(RUDevice, on_delete=models.CASCADE, null=False, blank=False, related_name='ru_magazine' )
    product_type = models.ForeignKey(ProductType, on_delete=models.CASCADE, null=False, blank=False, related_name='magazine_product_type')

class MagazineProduct(models.Model):
    magazine = models.ForeignKey(Magazine, on_delete=models.CASCADE, null=False, blank=False, related_name='magazine_product', help_text="Select magazine for product")

class ProductType(models.Model):
    brand = models.ForeignKey(ProductCompany, on_delete=models.CASCADE, null=False, blank=False, related_name='company', help_text="Select company name")
    size = models.ForeignKey(ProductSize, on_delete=models.CASCADE, null=False, blank=False, related_name='type_class', help_text="Select product class")

class Product(models.Model):
    sku = models.CharField(_("SKU"), max_length=100, blank=True, unique=True,help_text="Store ID")
    product_type = models.ForeignKey(ProductType, on_delete=models.CASCADE, null=False, blank=False, related_name='product_type', help_text="Select product type")
    count= models.PositiveIntegerField(default=0)

class SingleProduct(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE, null=True, blank=True, related_name='product', help_text="Select product")

我正在尝试过滤具有特定品牌的rudevices。它将返回杂志拥有该品牌的所有rurudevices。 我的第一个方法是这样。

for i in RUDevice.objects.all():
    mg = Magazine.objects.filter(device=i)

然后使用所有返回的mg过滤所有MagazineProduct。 MagazineProduct.objects.filter(magazine__in=mg, magazine__product_type__brand="Whisper")

如果我可以过滤magazineProduct,那么我可以得到rudevices。但是我得到ValueError: Field 'id' expected a number but got 'Whisper'. 我的方法还可以吗?

1 个答案:

答案 0 :(得分:1)

由于错误状态,它期望一个整数值或一个对象。但是,如果要搜索字符串,则可能是针对某个字段。假设它是name,则可以这样尝试:

MagazineProduct.objects.filter(
    magazine__device=i,
    magazine__product_type__brand__name="Whisper"
)

我删除了mg,并直接在i内使用MagazineProduct