[Answered ]-Filter All Objects That Belongs To a User From ForeignKey

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

Leave a comment