-1

I have a url field in 3 different models is there any pre defined way in rest framework or django so that they will be unique across multiple models?? or i have to write the whole unique thing logic manually?? and also these fields/models are not related to each other in any way not through foreignkey, manytomany or onetoone. They are diffrent models in which field names are same.

class City(models.Model):
    url = models.CharField() # Eg abc.com/indore
class State(models.Model):
    url = models.CharField() # Eg abc.com/madhya-pradesh
class Country(models.Model):
    url = models.CharField() # Eg abc.com/india

eg: A url used in a City object should not be used in any State and country objects as well

Arjun Ariyil
  • 386
  • 3
  • 14
Chip
  • 71
  • 1
  • 10
  • Does this answer your question? [What's the difference between django OneToOneField and ForeignKey?](https://stackoverflow.com/questions/5870537/whats-the-difference-between-django-onetoonefield-and-foreignkey) – Alvi15 Nov 19 '20 at 11:42
  • these fields are not related to each other in any way not through foreignkey, manytomany or onetoone – Chip Nov 19 '20 at 12:00

1 Answers1

1

One option is to override the clean() method of all models.

from django.core.exceptions import  ValidationError

class City(models.Model):
    url = models.CharField(unique=True) # Eg abc.com/indore

    def clean(self):
        if self.url:
            if State.objects.filter(url=self.url).exist():
                raise ValidationError({'url': ['Url already in use for a state']},
                                      code='invalid')
            elif Country.objects.filter(url=self.url).exist():
                raise ValidationError({'url': ['Url already in use for a country']},
                                      code='invalid')
        super().clean()

Do similar for State and Country Also

Arjun Ariyil
  • 386
  • 3
  • 14
  • thank you , ill use this instead manually writing everything in serializer. and im fairly new at this so i thought that there must be something like unique_together. – Chip Nov 19 '20 at 12:47