【问题标题】:How to filter the class to which the model is related in a ManyToManyField relation in Django?如何在Django的ManyToManyField关系中过滤模型相关的类?
【发布时间】:2020-04-04 21:03:03
【问题描述】:

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

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】:
    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?

    【讨论】:

    • 感谢您为我指明了正确的方向!不幸的是,我无法根据所选的 country 过滤 Location 模型
    • 我应该在admin.py 中创建一个新类吗?我应该在class CustomerAdmin(admin.ModelAdmin): 下添加方法吗?问题是 country 在这里不知道
    • 使用 kwargs["queryset"] = Location.objects.filter(exchange=request.country) 时会显示 'WSGIRequest' object has no attribute 'country'
    • 我找到了更好的解决方案,你可以使用 django_smart_selects。
    • 它会做你想要的。
    猜你喜欢
    • 2021-03-19
    • 2021-09-04
    • 2016-01-12
    • 2015-12-23
    • 2017-06-22
    • 1970-01-01
    • 1970-01-01
    • 2011-12-24
    • 2016-06-05
    相关资源
    最近更新 更多