Фильтрация объектов на основе состояния булевого поля
Я работаю над проектом, в котором заполняется форма. И в этой форме есть поля is_active. Если пользователь выбирает True, это означает, что аккаунт активен, а если False, это означает, что он больше не активен, и пользователь больше не может его видеть. Через фильтры я пытаюсь представить только те формы, в которых поле is_active True, но у меня не получается.
Следуйте за одной из моих попыток в моих взглядах:
class BookingViewSet(viewsets.ModelViewSet):
serializer_class = BookingSerializer
#queryset = Booking.objects.all()
#queryset = Booking.objects.filter(is_active="True")
#filter_backends = (filters.DjangoFilterBackend,)
#filterset_class = BookingFilter
#filterset_fields = ['is_active']
def get_queryset(self):
queryset = Booking.objects.all()
username = self.request.query_params.get('bookings')
if username is not None:
queryset = queryset.filter(is_active__username=username)
return queryset
и вот мои модели
class Booking(models.Model):
booking_id = models.AutoField(primary_key=True)
account = models.ForeignKey(Account, models.DO_NOTHING)
tenant = models.ForeignKey(Tenant, models.DO_NOTHING)
full_name = models.CharField(max_length=128)
email = models.CharField(max_length=256)
phone = models.CharField(max_length=256)
postal_code = models.CharField(max_length=64, null=True, blank=True)
from_city = models.CharField(max_length=256, null=True, blank=True)
to_city = models.CharField(max_length=256, null=True, blank=True)
travel_date = models.DateField()
travel_period = models.CharField(max_length=256, null=True, blank=True)
adults_travelers_count = models.SmallIntegerField()
children_travelers_count = models.SmallIntegerField()
senior_travelers_count = models.SmallIntegerField()
booking_request_description = models.TextField(blank=True, null=True)
booking_status_cd = models.CharField(max_length=10, null=True, blank=True)
locator_code = models.CharField(max_length=32, null=True, blank=True)
total_booking_price_atm = models.DecimalField(max_digits=11, decimal_places=2)
total_booking_cost_atm = models.DecimalField(max_digits=11, decimal_places=2)
payment_type_cd = models.CharField(max_length=10, null=True, blank=True)
payment_status_cd = models.CharField(max_length=10, null=True, blank=True)
payment_datetime = models.DateTimeField(blank=True, null=True)
discount_percent = models.DecimalField(max_digits=3, decimal_places=1)
discount_amount = models.DecimalField(max_digits=12, decimal_places=2)
payment_amount = models.DecimalField(max_digits=12, decimal_places=2)
voucher_file_path = models.TextField(blank=True, null=True)
receipt_file_path = models.TextField(blank=True, null=True)
invoice_file_path = models.TextField(blank=True, null=True)
modified_ts = models.DateTimeField()
modified_by = models.CharField(max_length=31)
modified_op = models.CharField(max_length=1)
created_by = models.CharField(max_length=31)
created_ts = models.DateTimeField()
is_active = models.BooleanField()
class Meta:
managed = True
db_table = 'booking'
unique_together = (("booking_id", "account", "tenant"),)
def get_queryset(self):
queryset = []
user = self.request.user
if user.is_authenticated:
bookings = Bookings.objects.all()
for i in bookings:
if i.is_active
queryset.append(i)
return queryset
Это должно сделать это!!!
По сути, вы правы, что фильтр Booking.objects.filter(is_active=True)
даст вам все активные бронирования. Если вы также хотите фильтровать по имени пользователя, вам нужно иметь еще один фильтр (можно через запятую в той же функции фильтрации) для фильтрации по нему. Неясно, где в ваших моделях находится username
, но если предположить, что в модели учетной записи:
Booking.objects.filter(is_active=True, account__username=username)