1π
It is not correct to do this on the model, you want to do it on the form.
If you already know the user instance for the form, you can do it at the class level with the queryset
kwarg (when you are defining the field):
client = forms.ModelChoiceField(queryset=MyClients.objects.filter(user=my_user))
However, if you only have access to the user instance at the create time, then you can still override the queryset later (usually in __init__
):
self.fields['client'].queryset = MyClients.objects.filter(user=my_user)
π€wim
1π
In the form part add a init function:
class MyForm(forms.Form, FormMixin):
def __init__(self, *args, **kwargs):
user = kwargs.pop('user', None)
self.user = user
super(MyForm, self).__init__(*args, **kwargs)
# do stuff
self.fields['myclient'].queryset = user.myclient_set.all()
Then in the view part add user=request.user
as form arg.
def my_view(request, id=None):
# do stuff to get your instance
form = MyForm(request.POST or None, instance=instance, user=request.user)
π€christophe31
0π
You can use the related name:
# Gets all MyClient objects for a user
user.myclient_set.all()
Iβm not entirely sure why you want to do this on the model, the place for this sort of logic is the form.
π€ptr
- [Answered ]-Applying conditional in Django CharFields interaction
- [Answered ]-Include Specific Foreign Keys in DRF Serializer
- [Answered ]-Django: How to filter patients from one department?
- [Answered ]-How to update serialized data on valid?
- [Answered ]-Asynchronously update page with data that are stored by middleware
Source:stackexchange.com