How to have a Django relational database with four tables? - python

I am creating a website using Django and have a problem with the database!
I have four tables (topics, questions, answers, and images). Each one of these tables has an id column and I would like to connect these four tables together.
I have tried to use a ForeignKey() but that didn't work out. I am receiving an error message. I don't know if I can use ManyToManyField() in this case, because it is only one column that I am trying to connect.
This is the code:
from django.db import models
# Create your models here.
class topics(models.Model):
topic_id = models.AutoField(primary_key=True)
topic_level = models.BooleanField()
topic_name = models.TextField()
class questions(models.Model):
question_id = models.AutoField(primary_key=True)
description = models.TextField()
questions_type = models.BooleanField()
class answers(models.Model):
answer_id = models.AutoField(primary_key=True)
description = models.TextField()
class images (models.Model):
image_id = models.AutoField(primary_key=True)
image_blob = models.BinaryField()
This is the code with the ForeignKey():
from django.db import models
# Create your models here.
class topics(models.Model):
topic_id = models.AutoField(primary_key=True)
topic_level = models.BooleanField()
topic_name = models.TextField()
topic_question = models.ForeignKey(questions, on_delete=CASCADE)
topic_answer = models.ForeignKey(answers, on_delete=CASCADE)
topic_image = models.ForeignKey(images, on_delete=CASCADE)
class questions(models.Model):
question_id = models.AutoField(primary_key=True)
description = models.TextField()
questions_type = models.BooleanField()
question_topic = models.ForeignKey(topics, on_delete=CASCADE)
question_answer = models.ForeignKey(answers, on_delete=CASCADE)
question_image = models.ForeignKey(images, on_delete=CASCADE)
class answers(models.Model):
answer_id = models.AutoField(primary_key=True)
description = models.TextField()
answer_topic = models.ForeignKey(topics, on_delete=CASCADE)
answer_question = models.ForeignKey(questions, on_delete=CASCADE)
answer_image = models.ForeignKey(images, on_delete=CASCADE)
class images (models.Model):
image_id = models.AutoField(primary_key=True)
image_blob = models.BinaryField()
image_topic = models.ForeignKey(topics, on_delete=CASCADE)
image_question = models.ForeignKey(questions, on_delete=CASCADE)
image_answer= models.ForeignKey(answers, on_delete=CASCADE)
And this is the error message that I am receiving:
topic_question = models.ForeignKey(questions, on_delete=CASCADE)
NameError: name 'questions' is not defined

At the point you're trying to use the question class name for indicating the related model, such class is not defined, as the error states. When you're referencing a model that is defined later in the code you must enclose the name in "":
topic_question = models.ForeignKey("questions", on_delete=CASCADE)
Here is the related docs: https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ForeignKey

Related

problem with django multitable inheritance and django-parler

i have these models:
class Product(TranslatableModel):
productId = models.UUIDField(default=uuid4, primary_key=True, editable=False)
translations = TranslatedFields(
title = models.CharField(max_length=100),
description = models.TextField(max_length = 2000)
)
picture = models.ImageField()
price = models.FloatField()
art_type = models.ForeignKey(ArtType, on_delete=models.SET_NULL, null = True,blank = True)
createdAt = models.DateTimeField(auto_now_add=True)
updatedAt = models.DateTimeField(auto_now=True)
purchase_num = models.PositiveBigIntegerField()
objects = InheritanceManager()
class Course(Product):
languages = models.ManyToManyField(Language)
isChaptersOpen = models.BooleanField(default=True)
but whenever i try to add a new course i get this error message in the django admin panel:
ImproperlyConfigured at /en/admin/products/product/
InheritanceQuerySet class does not inherit from TranslatableQuerySet
why this is happening

Django FileNotFoundError when trying to add an item to a model

I am trying to create some models using Django and python. All my models are working and I can add items to the models, except for my User model. Can anyone suggest what could be wrong about it?
models.py
from django.db import models
# Create your models here.
class Item(models.Model):
ID = models.IntegerField(auto_created=True, primary_key=True, unique=True)
Name = models.CharField(max_length=30)
Price = models.IntegerField()
class User(models.Model):
ID = models.IntegerField(auto_created=True, primary_key=True)
Nickname = models.CharField(max_length=50)
Password = models.CharField(max_length=200)
Mail = models.EmailField()
Points = models.IntegerField()
SaleItem = models.ForeignKey(Item, on_delete=models.CASCADE)
ProfilePic = models.FilePathField()
BannerPic = models.FilePathField()
ZodiacSign = models.CharField(max_length=50)
class Friendship(models.Model):
ID = models.IntegerField(auto_created=True, primary_key=True, unique=True)
UserID = models.ManyToManyField(User, related_name="user")
FriendID = models.ManyToManyField(User, related_name="befriended_user")
class ThreadPrivate(models.Model):
ID = models.IntegerField(auto_created=True, primary_key=True, unique=True)
Text = models.TextField()
Sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name="Sender")
Receiver = models.ForeignKey(User, on_delete=models.CASCADE, related_name="Receiver")
Time = models.DateTimeField(auto_now_add=True)
class Side(models.Model):
ID = models.IntegerField(auto_created=True, primary_key=True, unique=True)
Creator = models.ForeignKey(User, on_delete=models.CASCADE, related_name="creator_of_page")
Time = models.DateTimeField(auto_now_add=True)
class ThreadPublic(models.Model):
ID = models.IntegerField(auto_created=True, primary_key=True, unique=True)
Text = models.TextField()
Time = models.DateTimeField(auto_now_add=True)
Sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name="thread_sender")
SideID = models.ForeignKey(Side, on_delete=models.CASCADE, related_name="side_for_thread")
and admin.py
from django.contrib import admin
from .models import *
# Register your models here.
admin.site.register(Item)
admin.site.register(User)
admin.site.register(Friendship)
admin.site.register(ThreadPrivate)
admin.site.register(Side)
admin.site.register(ThreadPublic)
I have remembered to add to APPS in settings.py and such. All models work,
except for the User model. Any ideas?
picture of the error:
You have to provide a path to the FilePathField of the user model. According to this answer you could create the variable FILE_PATH_FIELD_DIRECTORY in your settings and then use it like:
from django.conf import settings
class User(models.Model):
ProfilePic = models.FilePathField(path=settings.FILE_PATH_FIELD_DIRECTORY)
It would be helpful to change the name of your class to CustomUser, so you don't confuse it with the User class from django.

I have extended the default User table named UserProfile and want to access info from Product model but shown integrity error

UserProfile table: (Extended table of default User)
from django.db import models
from django.contrib.auth.models import User
from django.db.models.deletion import CASCADE`enter code here`
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=CASCADE)
k_name = models.CharField(max_length=100, default="krishok Name", null=True)
k_address = models.CharField(max_length=300, default="Goes Krishok Address Here", null=True, blank=True)
k_national_id_no = models.CharField(default="1", max_length=50)
k_phone = models.CharField(default="01778956098", max_length=20)
k_email = models.EmailField(default="xxx#gmail.com", max_length=254)
k_image = models.ImageField(default = '', upload_to = 'upload/pkrishokImage/')
national_id = models.ImageField(default= '',upload_to = 'upload/IDImage/')
Product model code:
from Store.models.userprofile import UserProfile
from django.db import models
from .categories import Category
from .unit_type import Unit_Type
class Product(models.Model):
name = models.CharField(max_length=50)
category = models.ForeignKey(Category, on_delete=models.CASCADE, default=1)
unit= models.ForeignKey(Unit_Type, on_delete=models.CASCADE, default=1)
Unit_price = models.IntegerField(default=0)
#k_name = models.ForeignKey(UserProfile, on_delete=models.CASCADE)#this is the problem
quantity = models.IntegerField(default=0)
description = models.CharField(max_length=200, default='', null=True, blank=True)
image = models.ImageField(upload_to = 'upload/productsImg/')
#staticmethod
def get_all_products():
return Product.objects.all()
#Filtering by Category Id:
# this method will bring all products by its categoryID
#staticmethod
def get_all_products_by_id(category_id):
if category_id:
return Product.objects.filter(category = category_id)
else:
return Product.get_all_products()
#i am trying to get id from extended user table called UserProfile model and want to get access of #all data from Product model, so that i am trying to written my foreignKey at product table from UserProfile table but it's give me integrity error.

In Django restframework, foreign key value is not getting in HyperlinkedModelserializer

Models.py
from django.db import models
class BusinessType(models.Model):
method = models.CharField(max_length=25)
class Vendor(models.Model):
first_name = models.CharField(max_length=25)
middle_name = models.CharField(max_length=25)
last_name = models.CharField(max_length=25)
nick_name = models.CharField(max_length=10)
email = models.CharField(max_length=30)
company = models.CharField(max_length=25)
phone = models.CharField(max_length=15)
mobile = models.CharField(max_length=10)
fax = models.CharField(max_length=10)
billing_address_street = models.CharField(max_length=120)
billing_address_city = models.CharField(max_length=20)
billing_address_state = models.CharField(max_length=20)
billing_address_zip = models.CharField(max_length=6)
billing_address_country = models.CharField(max_length=20)
shipping_address_street = models.CharField(max_length=120)
shipping_address_city = models.CharField(max_length=20)
shipping_address_state = models.CharField(max_length=20)
shipping_address_zip = models.CharField(max_length=6)
shipping_address_country = models.CharField(max_length=20)
notes = models.CharField(max_length=120)
gstin = models.CharField(max_length=25, null=True)
tin = models.CharField(max_length=25, null=True)
business_type = models.ForeignKey(BusinessType, on_delete=models.CASCADE)
Serializers.py
from rest_framework import serializers
from .models import Vendor,BusinessType
class BusinessTypeSerializer(serializers.HyperlinkedModelSerializer):
[enter image description here][1]
class Meta:
model = BusinessType
fields = ('id','method')
class VendorSerializer(serializers.HyperlinkedModelSerializer):
business_type = serializers.CharField(source='business_type.method')
class Meta:
model = Vendor
fields = ('id','first_name','middle_name','last_name','nick_name','email','company','phone','mobile','fax','billing_address_street','billing_address_city','billing_address_state','billing_address_zip','billing_address_country','shipping_address_street','shipping_address_city','shipping_address_state','shipping_address_zip','shipping_address_country','notes','gstin','tin','business_type')
In Django restframework, foreign key value is not getting in HyperlinkedModelserializer in 'business_type' field. When I tried to post method after declaring foreign key field, it says:
"AssertionError: The .create() method does not support nested
writable fields by default. Write an explicit .create() method for
serializer UserSerializer, or set read_only=True"

Multiple foreign keys to the same id. Django. Design Patterns

I really can't figure out why I can't point by Foregin Key the exactly same id multiple times.
I'm trying to use Django ORM to the database that already exists.
And it looks like this:
I wanted to create model according to that:
class TestID(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=250)
test_case_id = models.CharField(max_length=250, unique=True)
module = models.CharField(max_length=50)
full_description = models.TextField()
class Meta:
db_table = "TestID"
class TestCaseRun(models.Model):
id = models.AutoField(primary_key=True)
soft_version = models.CharField(max_length=50)
automated_test_case_version = models.CharField(max_length=50, unique=True)
start_time = models.DateTimeField()
end_time = models.DateTimeField()
checksum = models.CharField(max_length=250)
result = models.CharField(max_length=50)
test_case_id = models.ForeignKey(TestID, db_column='test_case_id')
class Meta:
db_table = "TestCaseRun"
class TestStep(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=250, null=False)
result = models.CharField(max_length=50)
description = models.CharField(max_length=250)
start_time = models.DateTimeField()
end_time = models.DateTimeField()
test_case = models.ForeignKey(TestCaseRun, db_column='id')
class Meta:
db_table = "TestStep"
class single_check(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=250)
comparison = models.CharField(max_length=5, null=False)
expected = models.CharField(max_length=50, null=False)
actual = models.CharField(max_length=50, null=False)
result = models.CharField(max_length=50)
comment = models.CharField(max_length=250)
event_time = models.DateTimeField()
test_step_id = models.ForeignKey(TestStep, db_column='id')
class Meta:
db_table = "single_check"
class action(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=250)
type = models.CharField(max_length=5, null=False)
result = models.CharField(max_length=50)
comment = models.CharField(max_length=250)
event_time = models.DateTimeField()
test_step_id = models.ForeignKey(TestStep, db_column='id')
class Meta:
db_table = "action"
class logs(models.Model):
id = models.AutoField(primary_key=True)
msg = models.CharField(max_length=350)
type = models.CharField(max_length=5, null=False)
result = models.CharField(max_length=50)
comment = models.CharField(max_length=250)
event_time = models.DateTimeField()
test_step_id = models.ForeignKey(TestStep, db_column='id')
class Meta:
db_table = "logs"
When I try to run that code I get errors:
ERRORS:
web_report.TestStep: (models.E007) Field 'test_case' has column name 'id' that is used by another field.
HINT: Specify a 'db_column' for the field.
web_report.action: (models.E007) Field 'test_step_id' has column name 'id' that is used by another field.
HINT: Specify a 'db_column' for the field.
web_report.logs: (models.E007) Field 'test_step_id' has column name 'id' that is used by another field.
HINT: Specify a 'db_column' for the field.
web_report.single_check: (models.E007) Field 'test_step_id' has column name 'id' that is used by another field.
HINT: Specify a 'db_column' for the field.
And I really can not figure out why I can't point by Foregin Key the exactly same id multiple times. Imho nothing is wrong with this design. But I'm beginner in relational database design.
It looks like you are using the db_column argument incorrectly. This is the field on the model that you are linking from, not the column on the model that you are linking to. You cannot use db_column='id', because there is already a primary key id for each model.
Taking your TestStep model as an example:
class TestStep(models.Model):
id = models.AutoField(primary_key=True)
...
test_case = models.ForeignKey(TestCaseRun, db_column='id')
Your diagram shows that it is the test_case_id column that links to the TestCase model. So you should have:
test_case = models.ForeignKey(TestCaseRun, db_column='test_case_id')
or because that is the default, simply
test_case = models.ForeignKey(TestCaseRun)

Categories

Resources