Bypassing the unique constraint when defining a foreign key to just one field in Django

Viewed 88

I've a model as shown below:

class Instance(models.Model):
    data_version = models.IntegerField(default=1, unique=True)
    name = models.CharField(max_length=200)

The data_version field has to be related to all other models in the application:

class Source(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=200)
    version = models.ForeignKey(Instance, on_delete=models.CASCADE, to_field='data_version', null=True)

The problem here is that Django requires the field data_version to be a unique field for me to be able to define such a relationship but that simply doesn't fit into my use case. I need to have multiple Instance objects in the app, each with version numbers starting from 1. What I'd like is to have a unique constraint on the combination of name and data_version but then Django doesn't allow defining Foreign key relationships as shown above. Is there a way I can bypass this restriction?

0 Answers
Related