Home > database >  How can I prevent row duplicates in Django when no field is unique?
How can I prevent row duplicates in Django when no field is unique?

Time:11-13

Upon saving an object, is there a simple way to prevent duplication when the combination of all the fields together have the same data?

The unique=True parameter doesn't seem to help here, because individually any of the data could be duplicated, but never all of them at the same time.

If statement with several and conditions does not seem to me like a smart way so I'm looking for a better approach. Does Django provide it? All I could find was related to one field or other being duplicated.

views.py

def collect(request):
    # Requests data from the API
    response = requests.get('url')
    data = json.loads(response.text)

# Filters wanted data from JSON and saves on the DB
    for key in data:
        if Item.objects.filter(model=key['properties']['model']).exists() == True and Item.objects.filter(number=key['properties']['number']).exists() and Item.objects.filter(model=key['properties']['city']).exists() == True and Item.objects.filter(number=key['properties']['number']).exists() and Item.objects.filter(model=key['properties']['state']).exists() == True:
            continue
        else:
            a = Item()
            a.model = key['properties']['model']
            a.number = key['properties']['number']
            a.timestamp = dateparse.parse_datetime(key['properties']['data_hora_gmt'])
            a.city = key['properties']['city']
            a.state = key['properties']['state']
            a.save()
    return HttpResponseRedirect(reverse("index"))

models.py:

class Item(models.Model):
    model = models.TextField()
    number = models.DecimalField(max_digits=5, decimal_places=2)
    timestamp = models.DateTimeField(auto_now=False, auto_now_add=False)
    city = models.TextField()
    state = models.TextField()

CodePudding user response:

You can use unique_together so:

class MyModel(models.Model):
  field1 = models.CharField(max_length=10)
  field2 = models.CharField(max_length=10)

  class Meta:
    unique_together = ('field1', 'field2',)
  • Related