两种型号的Django多对多关系

时间:2017-06-23 18:31:01

标签: python django

我正在构建一个小型Web应用程序,人们可以在其中加入节目,并显示他们在模板上加入了节目。但是,我当前的问题是,在我的User Profile模型中,我添加了几个节目,但Show模型对象并未显示用户配置文件是它的一部分。我怎样才能在Django中实现这个目标?

models.py:

from django.contrib.auth.models import User
from django.db import models
from django.db.models.signals import post_save


class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, unique=True, related_name='user')
    bio = models.TextField(max_length=500, blank=True)
    image = models.ImageField(blank=True, upload_to="uploads/profile")
    show = models.ManyToManyField('Show', blank=True)

    def __str__(self):
        return str(self.user)


    def create_user_profile(sender, instance, created, **kwargs):
        if created:
            UserProfile.objects.create(user=instance)

    post_save.connect(create_user_profile, sender=User)


class Show(models.Model):
    user = models.ForeignKey(User, null=True, blank=True)
    name = models.CharField(max_length=120, null=True, blank=True)
    description = models.TextField(max_length=500, null=True, blank=True)
    image = models.ImageField(null=True, blank=True, upload_to="uploads/show")
    venue = models.CharField(max_length=120, null=True, blank=True)
    date = models.DateField(null=True, blank=True)
    genre = models.CharField(max_length=120, null=True, blank=True)

    def __str__(self):
        return self.name

0 个答案:

没有答案