Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limit possible values for ForeignKey to a subset of models

I have the following model:

class SOA(models.Model):
    adviser = models.ForeignKey(User)
    ...

The adviser can not be any user, but a user which satisfies certain requirements (for example, a user which belongs to a certain group). This is relevant for example when dealing with forms: a dropdown to select the adviser shows me all users in the system, but I want to filter that and only show users which are actually advisers (which is defined, in this case, by belonging to an advisers group)

Is it possible to handle this kind of constraint at the model level? Or maybe when populating the select box in the form?

like image 714
blueFast Avatar asked Feb 08 '23 19:02

blueFast


1 Answers

You can use limit_choices_to init argument of ForeignKey class. For example:

adviser = models.ForeignKey(User, limit_choices_to={'is_staff': True})

For more complex queries, you can use Q objects:

..., limit_choices_to=Q(share_holder=True) | Q(distributor=True)
like image 194
Selcuk Avatar answered Feb 12 '23 15:02

Selcuk