Django有两个表的关系,但不是两者都 [英] Django two table relationship, but not both

查看:57
本文介绍了Django有两个表的关系,但不是两者都的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个称为Post的表。一个帖子可以包含2个视频或2张图像,但不能同时包含两者。帖子的表模式如下所示:

I have a table called Post. A post can have 2 videos or 2 images, but not both. The table schema for a post looks like this:

class Post(models.Model):
    user            = models.ForeignKey(User, on_delete=models.CASCADE)
    header          = models.CharField()
    created_at      = models.DateTimeField(auto_now_add=True)

我有两个看起来彼此相似的表:

I have two tables that look similar to each other:

class PostImage(models.Model):
    post = models.ForeignKey(Post, on_delete=models.CASCADE)
    img  = models.ImageField()


class PostVideo(models.Model):
    post = models.ForeignKey(Post, on_delete=models.CASCADE)
    video = models.FileField()

我如何创建和强制执行一种关系,即帖子最多可以包含2张图像或2张视频,但不能同时包含视频和图像时间?还是有更好的方法呢?

How do I create and enforce the relationship where a post can have maximum and minimum of 2 images or 2 videos, but it can't have both videos and images at the same time? Or is there a better way to do this?

推荐答案

另一种方法是添加 pre_save PostImage PostVideo 发出code>信号,并在此处检查您的条件:

Another method is to add a pre_save signal for both PostImage and PostVideo and check your conditions there:

@receiver(pre_save, sender=PostVideo)
@receiver(pre_save, sender=PostImage)
def post_validator(sender, instance, *args, **kwargs):
    images_count = instance.post.postimage_set.count()
    videos_count = instance.post.postvideo_set.count()
    if not (<your conditions met>):
        raise ValidationError('Conditions not met!')

这篇关于Django有两个表的关系,但不是两者都的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆