简体   繁体   中英

django model foreign key AttributeError

In my Django project, I have two apps : "music" and "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". I followed what I read in other post but I got an AttributeError when I make my migrations :

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

Here are my two models.py file : -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. And when I import user.models.xxxx it doesn't work in any apps.

Do you know where does the problem come from?

@AlexHall is on the right track here. Try changing music.py to

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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