我可以过滤表单中的对象吗.ManyToManyField是否等于在另一个字段中选择的值



我想在ManyToManyField上设置一个查询集,以获取ForeignKey等于另一个表单字段中ForeignKey集的所有对象。

class ProductAdminForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(ProductAdminForm, self).__init__(*args, **kwargs)
self.fields['variants'].queryset = Variant.objects.filter(variantCategory__productCategory__name_single='test')

这是有效的,它选择所有"Variant",其中variantCategory中productCategory的"name_single"值等于"test"。我想把"test"替换为等于这个形式中设置的productCategory的"name_equal"。

以下是一些代码,用于详细说明对象之间的关系。

class Variant(models.Model):
variantCategory = models.ForeignKey('VariantCategory')
class VariantCategory(models.Model):
productCategory = models.ForeignKey('ProductCategory')
class ProductCategory(models.Model):
name_single = models.CharField()

https://i.stack.imgur.com/RTOno.jpg

这显示了应将productCategory定义为等于.的字段

我意识到这有点难以解释,如果你们中的任何人需要额外的代码/信息,请告诉我!

此外,我只需要查询来获取productCategory等于另一个productCategory的所有对象。"name_equal"部分实际上并不重要,可能是对象的id!

我认为应该使用"form"中的实例。

试试这样的东西。

def __init__(self, *args, **kwargs):
super(ProductForm, self).__init__(*args, **kwargs) 
self.fields['variants'].queryset = Variant.objects.select_related('variantCategory__productCategory').filter(variantCategory__productCategory_id=self.instance.productCategory_id)

如果您添加新的Product,这个解决方案将不起作用,因为您没有实例(实例将只在内存中,而不是数据库中(,所以您无法匹配foreign_key。正如你所看到的,我添加了select_related。波纹管一些好的做法

  • 记得使用select_related

    Variant.objects.select_related('variantCategory__productCategory').filter(variantCategory__productCategory_id=instance.productCategory_id) 
    
  • 使用model.id 的model_id instad

    Variant.objects.select_related('variantCategory_productCategory'(.filter(variantCategory_productCategory_id=instance.productCategory_id(


如果您只需要查询来获取productCategory等于另一个productCategory的所有对象,请尝试以下操作:

myProductCategory = ProductCategory.objects.last()
Product.objects.filter(productCategory__id=myProductCategory.id)  

如果有效,请告诉我:(

相关内容

最新更新