【问题标题】:Django: Use limit_choices_to to limit choices in Admin menuDjango:使用 limit_choices_to 限制管理菜单中的选择
【发布时间】:2012-12-23 20:10:38
【问题描述】:

我在 Django 中有一个模型:

class Task(models.Model):  
    product = models.ForeignKey(Product)  
    content = models.OneToOneField(ContentDataSet)  

如果我只想在标准下拉选择列表的用户/管理员中显示尚未分配的ContentDataSet 选项并已分配给此任务选项,我如何将选项limit_choices_to= 用于content 字段?

我尝试使用limit_choices_to = {'task__isnull':True},但在这种情况下,我看不到已经分配给此任务的content 选项。

limit_choices_to = models.Q(task__isnull=True) | models.Q(task=self) 不起作用,因为 self 未定义

【问题讨论】:

    标签: python django model


    【解决方案1】:

    limit_choices_to 无法做到这一点。 但是您可以使用两种不同的方法都可以正常工作:

    1) 对于ForeignKeys,您可以使用formfield_for_foreignkey 来覆盖ModelAdmin 中的查询集,如下所示:

    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if request.user.is_superuser:
            return super(UserOwnerProtectorModelAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)
    
        if db_field.name == "task":
            # This next line only shows owned objects
            # but you can write your own query!
            kwargs["queryset"] = db_field.related_model.objects.filter(user=request.user)
        return super().formfield_for_foreignkey(db_field, request, **kwargs)
    

    2) 作为第二选择,这里有一个覆盖字段查询集的示例,它可以帮助您处理 OneToOne 字段: Django ForeignKey limit_choices_to a different ForeignKey id

    祝你好运!

    【讨论】:

      【解决方案2】:

      Limit_choices_to 是一个 Q 对象。 在文档中,您有一个对 ForeignKey 进行类似限制的示例:https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ForeignKey.limit_choices_to

      关于查询的更多信息在这里:https://docs.djangoproject.com/en/dev/topics/db/queries/

      【讨论】:

      • 当我使用limit_choices_to = {'task__isnull':True} 时,我只能看到'新鲜'content 没有分配给任何东西。在这种情况下,我无法编辑Task,因为我看不到已分配给此Task 选项。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-08
      相关资源
      最近更新 更多