Just Me
Just Me

Reputation: 125

models in Django issue with foreign key

I have project on Django and me need to create the model which will be foreign key from other if some value is true.

I'll try to explain. I have some model :

class SomeClass(models.Model):
    def __unicode__(self):
        return unicode(self.name)
    boolean = models.BooleanField(default=1
    name = models.CharField(max_length=64, unique=True)

class SomeClass2(models.Model):
    def __unicode__(self):
        return unicode(self.name)
    child_item = models.ForeignKey(SomeClass, to_field='name')

What I must do then child_item get name only if boolean is True.

Upvotes: 0

Views: 46

Answers (1)

Antoine Pinsard
Antoine Pinsard

Reputation: 35032

You can limit foreign key choices with limit_choices_to:

class SomeClass(models.Model):

    def __unicode__(self):
        return unicode(self.name)

    boolean = models.BooleanField(default=1)
    name = models.CharField(max_length=64, unique=True)

class SomeClass2(models.Model):

    def __unicode__(self):
        return unicode(self.name)

    child_item = models.ForeignKey(SomeClass, to_field='name',
                                   limit_choices_to={'boolean': True})

Upvotes: 1

Related Questions