I have the code bellow and i need that every QuerySet returns only models that are created by specific user. Has a way to do it for every single queryset?
Not “automatically”, and not by default. Regardless of the method being used, it’s still going to be up to you to ensure that your requirements are being followed.
You can create a custom manager that does add the required filter on each request, but it’s still up to you to ensure that that manager is being used, and that there aren’t any queries being written to bypass it. (See Managers | Django documentation | Django for more information about model managers.)
otherwise you need to deduce the id of the required user and use that to filter the queryset. Notice that you do not need to read the data from the database again because super().get_queryset() grabbed everything before. So, you only need to filter that
Yes, if you pass it in as a parameter to your call to the manager method.
Again - this isn’t something that Django does for you automatically. It’s going to be up to you to make this work as desired.
We took a slightly different approach.
We use CBVs, but not (directly) the Django-provided CBVs. We’ve created our own CBV child classes that are based on the Django CBVs, but implement our own custom get_queryset method that applies our security layer to all queries.
At this point i’m sending the current user to CardFormView to filter only banks registered by the user, as we see below:
CardForm:
class CardForm(forms.ModelForm):
def __init__(self, user, *args, **kwargs):
super(CardForm, self).__init__(*args, **kwargs)
for visible in self.visible_fields():
input_type = visible.field.widget.__class__.__name__
match input_type:
case 'Select':
visible.field.widget.attrs['class'] = 'custom-select'
case _:
visible.field.widget.attrs['class'] = 'form-control'
# recupera o usuário passado como parâmetro na view e recupera apenas os bancos que o usuário cadastrou
self.user = user
self.fields['id_bank_account'].queryset = BankAccountModel.objects.filter(
id_titular_user=self.user)
class Meta:
model = CardModel
fields = '__all__'
def clean_id_bank_account(self):
cleaned_bank_account = self.cleaned_data['id_bank_account']
if cleaned_bank_account == None:
raise ValidationError('O banco não pode ser vazio.', 'invalid')
return cleaned_bank_account
If you can show me how to do this i’ll be very grateful.