How to filter occupied models in one-to-one relationship in django admin

Let's say I have two models with according tables in DB.

One model is Man and another is Women. Let's say I wan't to model marriage relationship between man and woman. Let's say, that one man can marry one woman and vice versa. So we have one-to-one relationship between models.

I know how to do that, what I don't know is how to filter occupied man and woman in according django admin form field.


In your form you can modify/filter the queryset that gets passed to the ModelChoiceField that selects the man/woman and do queryset = Woman.objects.filter(man=None) or whatever to get the currently unmarried men.

As an aside, unless you're working exclusively for the church or in certain countries, you may want to modify your approach, as you can't currently account for gay marriage (or the Amish, for that matter). Also, having Man and Woman models smacks of uneccesary denormalisation, unless there is a specific reason why you've split them into two models you might be better served by just having a Person model with a gender attribute.

Edit: To expand on your comment, if we set up the models like you suggested-

class Woman(models.Model):
    age = models.IntegerField()

class Man(models.Model):
    age = models.IntegerField()
    woman = models.OneToOneField(Woman)

then you can access man.woman or and the queryset would work either way. Django handles that stuff for you when you use the OneToOneField

Need Your Help

Fullscreen Window in Windows - Remove Border?

winapi window fullscreen titlebar

Many Windows applications (games, web browsers, some editors, etc.) support fullscreen mode, in which the application's client area covers the entire screen.