Hello there,

I guess your example is not the best since this check could be defined on 
Author.Meta.constraints
directly but if you wanted to define such a check on Book anyway you'll 
have to define a function
and refer to it in the check constraint using Func.

Using RunSQL in your migrations

RunSQL("""
create or replace function author_age_gt(int, int) returns boolean as $$
select exists (
    select 1
    from "author"
    where id = $1 and age > $2
);
$$ language sql;
""")

And then you could define your CheckConstraint as

CheckConstraint(Func(F('author'), 18, function='author_age_gt'), 
name='age_check')

Cheers,
Simon

Le jeudi 14 novembre 2019 02:45:32 UTC-5, Olivier a écrit :
>
> Hello,
>
> Let say I want to enforce a database constraint saying a "book's author 
> age is over 18".
> As you may guess, books and authors are each described with a Model 
> subclass with a foreign key (in this example each book is written by a 
> single author) linking both.
>
> class Author(models.Model):
>     age = models.SmallIntegerField()
>
>
> class Book(models.Model):
>     author = models.ForeignKey(Author, on_delete=models.PROTECT)
>
>     class Meta:
>         constraints = [
>            models.CheckConstraint(check=models.Q(<WHATEVER>__gt=18), 
> name='age_check'),
>         ]
>
>
> I've tried replacing <WHATEVER> above with author_age or author__age.
> In both cases, makemigrations works but migrate fails with:
> django.core.exceptions.FieldError: Joined field references are not 
> permitted in this query
>
>
> Can I work around this ?
> Any working example ?
>
> Best regards
>
>

-- 
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+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/2fa2ba09-2323-4b4a-8e7c-0f0712c561e0%40googlegroups.com.

Reply via email to