简体   繁体   English

Django模型外键AttributeError

[英]django model foreign key AttributeError

In my Django project, I have two apps : "music" and "user" . 在我的Django项目中,我有两个应用程序: “ music”“ user”
I am trying to create a table in my app "music" as a joint table between the table "MusicPiece" and the table "Member" from the other app "user". 我试图在我的应用程序“ music”中创建一个表,作为表“ MusicPiece”和另一个应用程序“ user”的表“ Member”之间的联合表。 I followed what I read in other post but I got an AttributeError when I make my migrations : 我遵循了我在其他文章中阅读的内容,但是在进行迁移时遇到了AttributeError

AttributeError: module 'user.models' has no attribute 'Member'    

Here are my two models.py file : -in "music" : 这是我的两个model.py文件:-in“ music”:

from django.db import models
from django.utils import timezone
from user import models as user_models

class MusicPiece(models.Model):
    name = models.CharField(max_length=20)

class MusicPieceAuthorship(models.Model):
    user = models.ForeignKey(user_models.Member,
                             on_delete=models.CASCADE)
    music_piece = models.ForeignKey(MusicPiece,
                                    on_delete=models.CASCADE)

-in "user" : -在“用户”中:

from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from music import models as music_models


class Member(models.Model):
    user = models.OneToOneField(User)
    birth_date = models.DateField(null=True)
    avatar = models.ImageField()

The weirdest thing is that when I import music.models.MusiquePiece in user.models.py it works perfectly. 最奇怪的是,当我在user.models.py中导入music.models.MusiquePiece时 ,它的工作原理非常完美。 And when I import user.models.xxxx it doesn't work in any apps. 当我导入user.models.xxxx时,它在任何应用程序中均不起作用。

Do you know where does the problem come from? 您知道问题出在哪里吗?

@AlexHall is on the right track here. @AlexHall在这里是正确的轨道。 Try changing music.py to 尝试将music.py更改为

from django.db import models
from django.utils import timezone

class MusicPiece(models.Model):
    name = models.CharField(max_length=20)

class MusicPieceAuthorship(models.Model):
    from user.models import Member # Ugly but avoids circular imports

    user = models.ForeignKey(Member,
                             on_delete=models.CASCADE)
    music_piece = models.ForeignKey(MusicPiece,
                                    on_delete=models.CASCADE)

Also it doesn't look like you're actually using your music model in your member script so remove the line below to avoid further issues with circular imports. 同样,您似乎并没有在成员脚本中实际使用音乐模型,因此请删除以下行,以避免循环导入的进一步问题。

from music import models as music_models

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM