Reputation: 35
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
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 ModelForm
s and on the Django admin pages). You still can select Project
s 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