#CheckConstraint problems

24 messages · Page 1 of 1 (latest)

silent blade
#
class PinnedVideo(models.Model):
    pinned_video = models.OneToOneField(Video, on_delete=models.CASCADE)
    pinning_user = models.OneToOneField(CustomUser, on_delete=models.CASCADE)

    class Meta:
        constraints = [
            CheckConstraint(
                check = Q(pinned_video = F("pinning_user")),
                name = "user_and_video_author_same",
                )
        ]


Trying to make a constraint that will guarantee that the pinned_videos author is the same as the pinning user, but just cant get it to work.

#

Other approach i considered is adding a bool field to a video called isPinned

#

and then allowing only one isPinned = True for each user

dusty epoch
#

pinned_video is a Video, pinning_user is a User, Check constraints do not cross tables.

#

I assume you have a Video.user field that denote the author ?

#

if your plan is to enforce this on a "Database" level, then your options would be to either create a trigger OR add the author to the PinnedVideo model and add a check constraint similar to the above but against the author.

silent blade
silent blade
#

How would I add the author to the pinnedvideo model?

dusty epoch
#

manually, same as you did above.

silent blade
#
 author = models.ForeignKey(CustomUser, on_delete=models.CASCADE)

this is the author in my video model

#

do u mean that i should just add that field to my PinnedVideo model?

dusty epoch
#

You could do it via save or via a signal, so long as you know that bulk operations do not call these.

#

yes, if you plan on enforcing on database level, you'll have to add the author to the PinnedVideo as well.

#

remember, this isn't a django limitation, this is an sql databases limitation.

silent blade
#
from django.db import models

from customusers.models import CustomUser
from videos.models import Video
from django.db.models import F, Q, CheckConstraint

class PinnedVideo(models.Model):
    pinned_video = models.OneToOneField(Video, on_delete=models.CASCADE)
    pinning_user = models.OneToOneField(CustomUser, on_delete=models.CASCADE)
    author = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name= "author", null=True)

    class Meta:
        constraints = [
            CheckConstraint(
                check = Q(pinned_video = F("author")),
                name = "user_and_video_author_same",
                )
        ]

``` did this and atm getting a 
InternalError at /admin/pinnedvideos/pinnedvideo/add/
current transaction is aborted, commands ignored until end of transaction block
error
#

or did u mean compare the author against pinning_user?

dusty epoch
#

yes ofcourse, isn't that what you're trying to do ?

#

making sure that the pinning_user is the author ?

silent blade
#

Yeah just had a brainfart

#

my bad

#

that does work yeah

dusty epoch
#

it's all good, hope that works for you.

silent blade
#

Yeah