如何在Django的ManyToManyField关系中过滤与模型相关的类?

问题描述 投票:0回答:1

我想过滤与模型Location相关的类House。这个想法是基于管理面板中字段Location的值限制country的选择。是否有可能,如果可以,我该怎么做?

class House(models.Model):
    country = models.ForeignKey(Country,
                                 on_delete=models.CASCADE,
                                 related_name='country'
                                 )
    city = models.ManyToManyField(
        Location,
        related_name='city'
    )

[基本上,我想这样,但是Django抛出一个错误,说django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet

city = models.ManyToManyField(
    Location.objects.filter(country=country,
    related_name='city'
)
django
1个回答
1
投票
class HouseAdmin(admin.ModelAdmin):
    def formfield_for_manytomany(self, db_field, request, **kwargs):
        if db_field.name == "city":
             kwargs["queryset"] = Location.objects.filter(country=country)
        return super(HouseAdmin, self).formfield_for_manytomany(db_field, request, **kwargs)

Django filter many to many field in admin?

热门问题
推荐问题
最新问题