Ali Ezzeddine
Ali Ezzeddine

Reputation: 35

Listing only specific values in OneToOneField Django

I have two models. The first one is a tools/models.py and the second one is projects/models.py. The tools model has a OneToOneField which refer to my projects model.

from django.db import models
from projects.models import Project


# Create your models here.
class ScrewDriver(models.Model):
   screwdriver_name = models.CharField(max_length=100, unique=True)
   screwdriver_project = models.OneToOneField(Project,on_delete=models.DO_NOTHING, null=True, blank=True)

But I don't want to show the project's name if the project status IS 'DONE'

from django.db import models


# Create your models here.
class Project(models.Model):
    status = [
        ('0', 'Paused'),
        ('1', 'On Going'),
        ('2', 'Done'),
    ]
    project_name = models.CharField(max_length=100, unique=True)
    project_status = models.CharField(max_length=1, choices=status)

So how can I set a condition before adding the models.OneToOneField ?

Thanks..

Upvotes: 1

Views: 99

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476594

You can work with the limit_choices_to=… parameter [Django-doc]:

from django.db.models import Q

class ScrewDriver(models.Model) :
    screwdriver_name = models.CharField(max_Length=100, unique=True)
    screwdriver_project = models.OneToOneField(
        Project,
        on_delete=models.DO_NOTHING,
        null=True,
        blank=True,
        limit_choices_to=~Q(project_status='2')
    )

This however only has effect on validating the form (so in ModelForms and on the Django admin pages). You still can select Projects that are done with the Django ORM, and furthermore if a project is later set to done, it will still link to that project.

Upvotes: 1

Related Questions