【问题标题】:Django: Select from the dropdown the object that has the field is_active=TrueDjango:从下拉列表中选择具有字段 is_active=True 的对象
【发布时间】:2021-02-26 20:08:08
【问题描述】:

我是一个使用 django 的新手,我有一个无法解决的问题。 在我的 ServiceCreateView 中,我需要从下拉列表中选择具有字段 is_active = true 的对象汽车, 我怎样才能做到这一点?

class Car(models.Model):
    brand = models.charfield(...)
    is_active= models.BooleanField(default=True)

class Service(models.Model):
    car = models.ForeingKey('Car'....)
    name = models.Charfield()

class ServiceCreateView(CreateView):
    model = Service
    form = ServiceForm
    ...

如果我在 Car 模型中将字段 is_active 更改为 false,则不应显示在下拉列表中。 有人能把我引向正确的方向吗?

【问题讨论】:

    标签: python django django-class-based-views


    【解决方案1】:

    我就是这样解决的

    from django import forms
    from .models import Service, Car
    
    
        class ServiceForm(forms.ModelForm):
        
            def __init__(self, *args, **kwargs):
                super().__init__(*args, **kwargs)
                self.fields['car'].queryset = Car.objects.filter(is_active=True)
        
            class Meta:
                model = Service
                fields = ('car', 'name')
    

    【讨论】:

      【解决方案2】:

      您可以使用limit_choices_to=… parameter [Django-doc] 限制选择:

      类服务(models.Model):
          汽车 = 模型.ForeingKey(
              '车',
              on_delete=models.CASCADE,
              limit_choices_to={'is_active': True}
          )
          name = models.Charfield()

      在数据库级别强制执行。因此,这意味着如果您通过视图构造一个Service 对象并选择一个Car,此时is_active=True,那么如果稍后将Car 设置为is_active=False,那么Service记录将仍然存在并指向不活动的Car。因此,这只会对 Django/Python 层产生影响,它只会显示 is_active=TrueCars,此外,ModelForm 将反映选择不活动的 Cars。

      【讨论】:

      • 谢谢!这是解决我的问题的另一种方法... :)
      • @ApoloMachine: 好吧,如果它应该用于(几乎)所有表格,我会在Service 模型中设置它,因为那时不需要更改所有ModelForms,并且ModelAdmin 也将使用它(您当然可以为ModelAdmin 定义一个自定义ModelForm,但这是更多的工作),如果它更像是一次性的,那么在@987654339 中设置它@ 更有意义:)。
      猜你喜欢
      • 1970-01-01
      • 2021-12-13
      • 2019-06-14
      • 1970-01-01
      • 2019-05-19
      • 1970-01-01
      • 2021-08-25
      • 1970-01-01
      • 2017-01-27
      相关资源
      最近更新 更多