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
Related
I want to be able to do queries involving multiple inner joins using Django ORM, here's my model (showing only relevant fields)
class Students(models.Model):
class Status(models.IntegerChoices):
preRegistered = 0 #No ha aceptado terminos y condiciones
Enabled = 1
Disabled = 2
Suspended = 3
Test = 4
id = models.AutoField(primary_key=True)
user = models.ForeignKey(Users, on_delete=models.CASCADE)
trainingPath = models.ForeignKey(trainingPaths, on_delete=models.CASCADE)
status = models.IntegerField(choices=Status.choices, default=0)
creationDate = models.DateTimeField(auto_now_add=True)
modificationDate = models.DateTimeField(auto_now=True)
class Meta():
db_table = 'Students'
class trainingPaths(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=70, blank=False, null=False)
shortName = models.CharField(max_length=10, blank=True)
creationDate = models.DateTimeField(auto_now_add=True)
modificationDate = models.DateTimeField(auto_now=True)
class Meta():
db_table = 'Training_Path'
class Courses(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=70, blank=False, null=False)
path = models.URLField(max_length=500, blank=True, null=True)
shortName = models.CharField(max_length=6, blank=True)
creationDate = models.DateTimeField(auto_now_add=True)
modificationDate = models.DateTimeField(auto_now=True)
course_image = models.URLField(max_length=200, blank=True)
class Meta():
db_table = 'Courses'
class CoursesXTrainingP(models.Model):
id = models.AutoField(primary_key=True)
trainingPath = models.ForeignKey(trainingPaths, on_delete=models.CASCADE)
course = models.ForeignKey(Courses, on_delete=models.CASCADE)
alternativeName = models.CharField(max_length=70, blank=True)
order = models.PositiveIntegerField(blank=False)
creationDate = models.DateTimeField(auto_now_add=True)
modificationDate = models.DateTimeField(auto_now=True)
class Meta():
db_table = 'Courses_X_Training_Paths'
I want to get the information of the courses that a student has according to the value of the "trainingPath".
this is my SQL query
select
courses.id, courses.`name`, courses.course_image
from
students
join
courses_x_training_paths
on
students.trainingPath_id = courses_x_training_paths.trainingPath_id
join
courses
on
courses_x_training_paths.course_id = courses.id
where
students.trainingPath_id=1;
I have tried several ways and none of them have worked, could you please help me?
You can filter with:
Courses.objects.filter(
coursesxtrainingp__trainingPath_id=1
)
The join on the Students model is not necessary, since we already know that the trainingPath_id is one by filtering on the CoursesXTrainingP model.
Note: normally a Django model is given a singular name, so Student instead of Students.
Note: normally the name of the fields in a Django model are written in snake_case, not PascalCase, so it should be: modification_date instead of modificationDate.
i have 3 models in django like this:
class SlackConfigurationMode(models.Model):
MODES = (
("NORMAL", "normal"),
("ALERT", "alert"),
("DANGER", "danger")
)
mode = models.CharField(choices=MODES, default=MODES[0][0], max_length=20)
time_send_slack_notification_minute = models.IntegerField(default=0)
time_send_slack_notification_hour = models.IntegerField(default=0)
description = models.TextField(blank=True)
class WebHookConfiguration(models.Model):
webhook_url = models.CharField(max_length=100)
slack_configuration_mode = models.ForeignKey(
SlackConfigurationMode,
on_delete=models.CASCADE,
related_name='webhook_configurations'
)
class MonitorSource(models.Model):
TYPES = (
("FACEBOOK", "facebook"),
("WEBSITE", "website"),
("YOUTUBE", "youtube")
)
target = models.CharField(max_length=100)
type = models.CharField(choices=TYPES, max_length=20)
created_at = models.DateTimeField(auto_now_add=True)
owner = models.ForeignKey("auth.User", on_delete=models.CASCADE)
name = models.CharField(max_length=100)
slack_configuration = models.ForeignKey(
SlackConfigurationMode, on_delete=models.DO_NOTHING,
default=SlackConfigurationMode.objects.filter(mode="NORMAL")[0].id,
related_name='monitor_sources'
)
i want to get data of webhook_configuration and monitorsource filter by slackconfiguration by mode
i use this query:
queryset = SlackConfigurationMode.objects.select_related('webhook_configurations', 'monitor_sources').filter(
mode='HIGH'
)
but have the error:
Invalid field name(s) given in select_related: 'monitor_sources', 'webhook_configurations'. Choices are: (none)
how can i fix it, and why my query won't work, tks
Here, webhook_configurations and monitor_sources are reverese relations and hence you must use prefetch_related(...)
queryset = SlackConfigurationMode.objects \
.prefetch_related('webhook_configurations', 'monitor_sources') \
.filter(mode='HIGH')
I want to use a raw query in order to make a JOIN in a many to many relationship, and show it in the Django Rest Framework.
But the "SELECT" part of the query is not working, and it shows whatever the serializer has in "fields" and thus the JOIN is also not working.
serializers.py:
class UserTestSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = "__all__"
views.py:
class UserTestQuery(viewsets.ModelViewSet):
queryset = User.objects.raw('SELECT * ' +
'FROM users_user ' +
'INNER JOIN sysadmin_works_as ON users_user.user_id = sysadmin_works_as.employee_id;')
serializer_class = UserTestSerializer
I want to show a join in the API with these 3 models, so I must use raw SQL. Why is it not working?
And the models I'm using are:
class User(AbstractUser):
first_name = None
last_name = None
username = None
user_id = models.AutoField(primary_key=True)
email = models.EmailField(_('email address'), unique=True)
national_id_number = models.CharField(max_length=30)
f_name = models.CharField(max_length=100)
l_name = models.CharField(max_length=100)
star_count = models.IntegerField(default=0)
created_at = models.DateTimeField(auto_now_add=True,null=True)
is_superuser = models.BooleanField(default = False)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
updated_at = models.DateTimeField(auto_now=True,null=True)
deleted_at = models.DateTimeField(blank = True, null=True)
date_joined = models.DateTimeField(auto_now_add=True,null=True)
app_role = models.ForeignKey(App_roles,related_name='employee',on_delete=models.SET_NULL,blank=True,null=True) #Un Rol_de_Aplicacion le pertenece a muchos usuar
class Works_as(models.Model):
work_id = models.AutoField(primary_key=True)
started_at = models.DateTimeField(auto_now_add=True)
updates_at = models.DateTimeField(auto_now=True)
r_created_at = models.DateTimeField(auto_now_add=True)
r_updated_at = models.DateTimeField(auto_now=True)
r_deleted_at = models.DateTimeField(auto_now=False,blank=True,null=True)
employee = models.ForeignKey(User,related_name='works_as',on_delete=models.SET_NULL,blank=True,null=True)
position = models.ForeignKey(Position,related_name='works_as',on_delete=models.SET_NULL,blank=True,null=True)
class Position(models.Model):
position_id = models.AutoField(primary_key=True)
name = models.CharField(max_length=100)
description = models.CharField(max_length=255)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
deleted_at = models.DateTimeField(blank=True,null=True)
upper_position = models.ForeignKey('self',on_delete=models.SET_NULL,blank=True,null=True)
department = models.ForeignKey(Department,related_name='positions',on_delete=models.SET_NULL,blank=True,null=True)
hierarchy_level = models.OneToOneField(Employee_Hierarchy,related_name='position',on_delete=models.SET_NULL,blank=True,null=True)
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
I looked at a ton of these issues on stack overflow, but none of the solutions seemed to help me. I've tried Null=True and Blank=True as well as default=None and they all give errors. Anyone have any ideas? Thanks so much!
The error I'm getting is this:
NOT NULL constraint failed: first_app_trip.messages_id
My models:
class Trip(models.Model):
title = models.CharField(max_length = 50)
destination = models.CharField(max_length = 255)
description = models.TextField()
start_date = models.DateField(auto_now_add=False)
end_date = models.DateField(auto_now_add=False)
creator = models.ForeignKey(User, related_name="created_trips")
participants = models.ManyToManyField(User, related_name="joined_trips", default=None)
messages = models.ForeignKey(Message, related_name="messages", default=None )
notes = models.ForeignKey(Note, related_name="notes", default=None)
created_at = models.DateTimeField(auto_now_add = True)
updated_at = models.DateTimeField(auto_now_add = True)
class Message(models.Model):
content = models.TextField()
author = models.ForeignKey(User, related_name="author")
created_at = models.DateTimeField(auto_now_add = True)
updated_at = models.DateTimeField(auto_now_add = True)
class Note(models.Model):
content = models.CharField(max_length=45)
user = models.ForeignKey(User, related_name="notes")
My Views:
def create(request):
user = current_user(request)
print user.id
return render(request, 'first_app/create_trip.html')
def add(request):
user = current_user(request)
print user
trip = Trip.objects.create(
title = request.POST.get('title'),
destination = request.POST.get('destination'),
description = request.POST.get('description'),
start_date = request.POST.get('start_date'),
end_date = request.POST.get('end_date'),
creator = user
)
print trip
return redirect('/user_profile')
Python case sensitive
try it
class Trip(models.Model):
messages = models.ForeignKey(Message, related_name="messages", null=True, blank=True )
# in this line case sensitive ^^^^^^^^^^^^^^^^^^^
next:
./manage.py makemigrations first_app
./manage.py migrate first_app
after it try your action