1

I have two tables document (id, file) similarity(id1,id2,similarityvalue) where id1 and id2 are foreign keys to id of document table. I want to add a check in django(in the model) to make sure id1!=id2

Is there a way to add this in django.(sort of like adding a sql check).

1

1 Answer 1

1

From the Django Docs:

Model.clean()
""" This method should be used to provide custom model validation, and to 
modify attributes on your model if desired. For instance, you could use it to
automatically provide a value for a field, or to do validation that requires 
access to more than a single field: """

def clean(self):
    from django.core.exceptions import ValidationError

    if self.status == 'draft' and self.pub_date is not None:
        raise ValidationError('Draft entries may not have a publication date.')

So for your purposes you would write something like the following for your similarity model:

def clean(self):
    from django.core.exceptions import ValidationError
    if self.id1 == self.id2:
        raise ValidationError('Entries must compare different objects')
Sign up to request clarification or add additional context in comments.

2 Comments

Ya, I think this is one way to validate. But it would be good to see if anyone has come across a way to implement Sql check when creating the models. Also is there a way to run raw sql create statements?
You can run anything raw you want against your db just like normal. Keeping in mind that you need to produce an output that matches your models with whatever your customizations are. In fact even within your app you can run raw queries. That said I'm not sure why you would want to implement what sounds to me like business logic within your database rather than within your app. That just makes the code harder to maintain.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.