简体   繁体   中英

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.

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})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM