Friday, April 21, 2017

Re: First models.py needs tuning

Hi Rich,

On Fri, Apr 21, 2017 at 05:48:01AM -0700, Rich Shepard wrote:
> What about my other question? When I want to limit acceptable strings in a
> data entry field to a provided list, as in postgres's check constraint? Is
> Mike's suggestion of clean() the way to handle these?

As far as I know, there's no way to declare CHECK constraints in your
model definitions, at least not with vanilla Django. However, you can
still add those constraints in your migrations using RunSQL.

Anyway, that only takes care of database-level enforcement of such
constraints; however, if any of them get violated, you'll just get an
integrity error from the database. If you want to be able to
gracefully handle violations of those constraints, and produce more
meaningful error messages (for example, when validating a form that
processes one of these models), you'd also implement those checks in
Python, either in your models' clean methods, or if it's a constraint
only involving a single field, you can also just add a custom
validator to that field.

On Fri, Apr 21, 2017 at 09:41:05AM -0700, Rich Shepard wrote:
> I'll let Django do this. However, should I still specify unique_together()
> for the columns that would have comprised the PK?

Indeed – if you want to be certain that those natural keys are really
keys, you should list them in unique_together. That will enforce
uniqueness both with UNIQUE constraints in the table definition, as
well as higher-level validation in Python.

Cheers,

Michal

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/20170421215001.GW23772%40koniiiik.org.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment