django list of values

142 Views Asked by At

What is the best way to store a field that can take a subset of choices of another class?

I have a class with a field that is a list of choices:

class Type( models.Model):
   type = models.CharField(max_length=4, choices=TYPE_CHOICES, default='CONS')

and another class with a foreign key to Type that should store a subset of the choices:

class AnotherType( models.Model ):
   model_parameter = models.ForeignKey(Type, on_delete=models.CASCADE)
   subset = models.XXX( arbitrary subset of Type.type.TYPE_CHOICES )

Any help is appreciated!

1

There are 1 best solutions below

0
Brian On

A reverse ForeignKey, maybe. The related_name specified will allow any object to have multiple backward relations.

class Type( models.Model):
    type = models.CharField(max_length=4, choices=TYPE_CHOICES, default='CONS')
    another_type = models.ForeignKey('yourmodel.AnotherType', related_name='subset')

class AnotherType( models.Model ):
    model_parameter = models.ForeignKey(Type, on_delete=models.CASCADE)

Now, if you have the example modified to your needs, you can now do:

a = AnotherType.objects.first()
a.subset.all()  # Some of the types you associated with it