Django - User.Profile与另一个模型之间的多种关系,ValueError:无法添加

时间:2017-10-14 01:52:18

标签: python django django-models

用户/ models.py

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


class Bread(models.Model):
    title = models.CharField(max_length=40)

    def __str__(self):
        return self.title


class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    bio = models.TextField(max_length=500, blank=True)
    location = models.CharField(max_length=30, blank=True)
    birth_date = models.DateField(null=True, blank=True)
    picture = models.ImageField(upload_to="photos/", default="photos/none/default.png")
    bread = models.ManyToManyField(Bread)


@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)


@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
    instance.profile.save()

我尝试向Profile模型添加一个简单的对象,但它不起作用。

>>> from user.models import Bread
>>> from user.models import Profile
>>> from django.contrib.auth.models import User
>>> p1 = Bread(title="Example")
>>> p1.save()
>>> Profile(User).bread.add(p1)
ValueError: Cannot add "<Bread: Example>": instance is on database "None", value is on database "default"
>>> u1 = Profile(User)
>>> u1.save()
TypeError: _prepare() takes 1 positional argument but 2 were given

看到类似的先前问题我试图保存个人资料模型,正如你所看到的,我知道它与用户及其身份相关,但我不知道如何轻松修复它

2 个答案:

答案 0 :(得分:0)

您是否尝试完全创建Profile对象并在向其添加Bread实例之前保存它? 另外我注意到你正在将模型类传递给模型构造函数。您应该传递用户的实例。 您的个人资料模型还需要其他一些字段。

在创建它时,我会明确而非隐式:

u1 = Profile.objects.create(
    user=myuser,
    bio="blablabla",
    location="blublublue",
)

然后,只有这样,我才会将面包实例添加到Profile实例

希望它清楚。

答案 1 :(得分:0)

>>> from api.models import Film
>>> from user.models import Profile
>>> from django.contrib.auth.models import User
>>> from django.shortcuts import render, redirect, get_object_or_404
>>> user = get_object_or_404(Profile)
>>> user
<Profile: Profile object>
>>> lobster = get_object_or_404(Film, id=22)
>>> lobster
<Film: Lobster>
>>> a = user.film.add(lobster)
>>> another_movie = get_object_or_404(Film, id=23)
>>> another_movie
<Film: What I actually do>
>>> user.film.add(another_movie)
>>> film = bloader.film.all()
>>> film
<QuerySet [<Film: Lobster>, <Film: What I actually do>]>
>>>

我试过这样,它的工作,谢谢@efkin。