Django: Linking Models in different apps gives circular import error - django

I have two apps in my project names quiz_app_teacher and accounts
many models from these files are connected with each other, but when i try to migrate I get this error
File "F:\self\quiz_site\quiz_app_teacher\models.py", line 2, in
from accounts import models as account_models File "F:\self\quiz_site\accounts\models.py", line 13, in
class Student(models.Model): File "F:\self\quiz_site\accounts\models.py", line 15, in Student
quizzes = models.ManyToManyField(quiz_models.Quiz) AttributeError: partially initialized module 'quiz_app_teacher.models' has no
attribute 'Quiz' (most likely due to a circular import)
quiz_app_teacher/models.py
from django.utils import timezone
from accounts import models as account_models
from django.db import models
# Create your models here.
ANSWER_CHOICES = (
('A', 'A'),
('B', 'B'),
('C','C'),
('D','D'),
)
class Quiz(models.Model):
#https://www.sankalpjonna.com/learn-django/the-right-way-to-use-a-manytomanyfield-in-django
name=models.CharField(max_length=250)
quiz_id = models.CharField(max_length=300,)
created_date = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(account_models.User, on_delete=models.CASCADE,related_name='quizzes')
#Using related_names Author.quizzes.all()
#will list all the quizzes which are made by that author.
course = models.ForeignKey(account_models.Course, on_delete=models.CASCADE, related_name='quizzes')
def save(self, *args, **kwargs):
#override default save method to do something before saving object of model
if not self.quiz_id:
self.quiz_id = self.name+"-"+self.created_date.strftime("%M%S") #TODO:Edit this
super(Quiz, self).save(*args, **kwargs)
def __str__(self):
return self.name
class result(models.Model):
#quiz=models.OneToOneField(Quiz,on_delete=models.CASCADE)
student=models.ForeignKey(account_models.Student , on_delete=models.CASCADE,related_name='my_results')#maybe use account_models.User
quiz=models.ForeignKey(Quiz, on_delete=models.CASCADE, related_name='results')
points=models.IntegerField()
def __str__(self):
return f"Student name: { str(self.student)} Points:{ str(self.points)}"
class Question(models.Model):
quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE, related_name='questions')
#quiz=models.ForeignKey(Quiz, on_delete=models.CASCADE)
question=models.CharField(max_length=300,)
A = models.CharField(max_length=200,)
B = models.CharField(max_length=200,)
C = models.CharField(max_length=200,)
D = models.CharField(max_length=200,)
answer = models.CharField(max_length=200,choices=ANSWER_CHOICES,default='A')
question_number=models.IntegerField()
def __str__(self):
return self.question
accounts/models.py
from django.contrib.auth.models import AbstractUser
from django.db import models
import quiz_app_teacher.models as quiz_models
# Create your models here.
class Course(models.Model):
name = models.CharField(max_length=30)
Year=models.IntegerField()
def __str__(self):
return self.name
class User(AbstractUser):
is_teacher = models.BooleanField(default=False)
class Student(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
quizzes = models.ManyToManyField(quiz_models.Quiz)
course = models.ForeignKey(Course,on_delete=models.CASCADE, related_name='class_students')
def __str__(self):
return self.user.username
class Teacher(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
quizzes = models.ManyToManyField(quiz_models.Quiz)
def __str__(self):
return self.user.username
If i try to define relations using
quizzes = models.ManyToManyField(to='quiz_models.Quiz')
SystemCheckError: System check identified some issues:
ERRORS: accounts.Student.quizzes: (fields.E300) Field defines a
relation with model 'quiz_models.Quiz', which is either not installed,
or is abstract. accounts.Student.quizzes: (fields.E307) The field
accounts.Student.quizzes was declared with a lazy reference to
'quiz_models.quiz', but app 'quiz_models' isn't installed.
accounts.Student_quizzes.quiz: (fields.E307) The field
accounts.Student_quizzes.quiz was declared with a lazy reference to
quiz_models.quiz', but app 'quiz_models' isn't installed.

You can remove your imports and refer to your ForeignKey models like so:
models.ForeignKey('account_models.Course', ...)
This should allow you to run your migrations without a circular import
https://docs.djangoproject.com/en/4.0/ref/models/fields/#django.db.models.ForeignKey
Edit from OP:
Update: I fixed it by running migrations for both files simultaneously. python manage.py makemigrations accounts quiz_app_teacher

Related

Cannot import name ... from partially initialized module

For a few days, projects.models has been importing a model from companies.models
I added a line to import a model in reverse, from companies.models to projects.models - hit save - and was given this error
This error says projects.models cannot import from companies.model - even though it's been doing it for the past few days
if I delete the line that caused the error in the other app (companies.models), the error still remains
companies - models.py
from projects.models import (projects)
class companies(models.Model):
fk_user = models.ForeignKey(User, default='1', on_delete=models.CASCADE)
name = models.CharField(max_length=100, verbose_name="Name")
def __str__(self):
return self.name
class Meta:
ordering = ('id', )
projects - models.py
from companies.models import (companies) {CAUSED THE ERROR}
class projects(models.Model):
fk_user = models.ForeignKey(User, default='1', on_delete=models.CASCADE)
name = models.CharField(max_length=100, verbose_name="Name")
def __str__(self):
return self.name
class Meta:
ordering = ('id', )
Why after reverting it to how it's been for the last few days by removing the line causing the error, does it no longer work?

Cannot access field in Django Graphene

The field which is specified in my models file is not included in the GraphiQL, I have tried to rename the field, delete it and define it again, even changing the type of field also updating the graphene-django package. None of these I have mentioned didn't work. The name of the field I can't get is named book
models.py
from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
from books.models import Book
class Borrowing(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
book = models.OneToOneField(Book, null=True, on_delete=models.CASCADE)
date = models.DateTimeField(default=timezone.now)
returned = models.BooleanField(default=False)
date_borrowed = models.CharField(blank=True, null=True, max_length=50)
date_returned = models.CharField(blank=True, null=True, max_length=50)
class Meta:
ordering = ['-date']
def __str__(self):
return f'{self.user.username} borrowed {self.book.title}'
schema.py
import graphene
from .mutations.borrowings import *
from backend.functions import pagination
PAGE_SIZE = 12
class BorrowingMutation(graphene.ObjectType):
borrow_book = BorrowBook.Field()
return_book = ReturnBook.Field()
class BorrowingQuery(graphene.ObjectType):
borrowings = graphene.List(BorrowingType)
users_borrowings = graphene.List(BorrowingType, page=graphene.Int())
def resolve_borrowings(self, info):
return Borrowing.objects.all()
def resolve_users_borrowings(self, info, page):
user = info.context.user
borrowings = Borrowing.objects.filter(user=user, returned=False)
borrowings = pagination(PAGE_SIZE, page, borrowings)
return borrowings
Type
class BorrowingType(DjangoObjectType):
class Meta:
model = Borrowing

synonyms and antonyms in a django dictionary app for local language

sorry for this question, but I had a problem with making a dictionary app for a local language, so I wouldn't need English dictionary, my problem is synonyms, I can't figure out how to implement it in my models
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
# Create your models here.
class Voca(models.Model):
name = models.CharField(max_length=200, unique=True)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse("voca:detail", kwargs={"id": self.id, "name": self.name})
class Defination(models.Model):
voca = models.ForeignKey(Voca, related_name='definations')
defination = models.CharField(max_length=500)
example = models.CharField(max_length=500)
etymology = models.CharField(max_length=500)
author = models.ForeignKey(User, default=1)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
class Meta:
ordering = ('created',)
def __str__(self):
return 'Defination given by {} on {}'.format(self.author, self.voca)
class Synonym(models.Model):
words = models.ManyToManyField(Voca, blank=True, related_name='synonyms')
I would like for users to add words, synonyms, antonyms definitions to the database themselves since it is a slang language, so if I can get any help especially for antonyms and synonyms I would really appreciate... thanks
My suggestion would be to remove the Synonym model and add fields to your Defination model.
class Defination(models.Model):
voca = models.ForeignKey(Voca, related_name='definations')
...
synonyms = models.ManyToManyField(Voca, related_name='synonyms')
antonyms = models.ManyToManyField(Voca, related_name='antonyms')

how to populate django models randomly

I am following a tutorial online for Django. The presenter loads in random data as follows:
for i in xrange(100): Vote(link = Link.objects.order_by('?')[0],voter=a).save()
From what I could understand, it goes from 0 to 100 and creates a new vote. The vote object has a link object. I don't understand what the order_by('?') means.
Here is the model.py file:
from django.db import models
from django.contrib.auth.models import User
from django.db.models import Count
class LinkVoteCountManager(models.Manager):
def get_query_set(self):
return super(LinkVoteCountManager, self).get_query_set().annotate(
votes=Count('vote')).order_by("-votes")
class Link(models.Model):
title = models.CharField("Headline", max_length=100)
submitter = models.ForeignKey(User)
submitted_on = models.DateTimeField(auto_now=True)
rank_score = models.FloatField(default=0.0)
url = models.URLField("URL", max_length=250, blank=True)
description = models.TextField(blank=True)
with_votes = LinkVoteCountManager()
objects = models.Manager()
def __unicode__(self):
return self.title
class Vote(models.Model):
voter = models.ForeignKey(User)
link = models.ForeignKey(Link)
def __unicode__(self):
return "%s voted %s" %(self.voter.username, self.link.title)

Django __unicode__ extended Auth_User model

I'm extending a the auth.models.User but I'm having troubles to implement the __unicode__ methode.
from django.db import models
from django.contrib.auth.models import User
class Artist(models.Model):
user = models.OneToOneField(User)
city = models.CharField(max_length=30)
bio = models.CharField(max_length=500)
Now how to I access the user fields as I want to return the name for Django Admin.
class Artist(models.Model):
# fields
def __unicode__(self):
return "{first_name} {last_name}".format(
**dict(
first_name=self.user.first_name,
last_name=self.user.last_name
)
)
Though User already has a function to concat the name fields, so this will work too:
def __unicode__(self):
return "{0}".format(self.user.get_full_name())
Or even
def __unicode__(self):
return self.user.get_full_name()