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
Related
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
Hi I am trying to resolve my error issues that I am trying to filter in my customer template. In my views if I place entry_objects= Entry.objects.all(). It is fine, but I want to be able to filter by customer. My query set worked but I can't do reverse bottom to up. :(
Models.py:
class customer(models.Model):
name = models.CharField(max_length= 200, null = True)
phone = models.CharField(max_length= 200, null = True)
email = models.CharField(max_length= 200, null = True)
date_created = models.DateTimeField(auto_now_add=True, null= True)
def __str__(self):
return self.name
class UserTopic(models.Model):
#category for user to chose
#User interest
text = models.CharField(max_length=120, null =True) #we want to display characters with max 250
date_added = models.DateTimeField(auto_now_add=True, null=True ) #allows realtime accuracy upon upload
#string representation of model
def __str__(self):
return self.text
class Tag(models.Model):
tag_name = models.CharField(max_length=15, null=True)
def __str__(self):
return self.tag_name
#entry model
class Entry(models.Model):
cust_name = models.ForeignKey(customer, null= True, on_delete=models.SET_NULL)
tags = models.ForeignKey(Tag, null = True, on_delete=models.CASCADE)
topic = models.ForeignKey(UserTopic, null = True, on_delete=models.CASCADE)
text = models.TextField()
date_added = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.text[:10]+"..."
# ...
on_delete=models.DO_NOTHING,
Views.py:
def customer_page(request, pk_test):
customer_objects = customer.objects.get(id=pk_test),
entry_objects = customer.entry_set.all()
#entry = Entry.objects.all()
context = {
'entry_objects': entry_objects,
'customer_objects': customer_objects,
}
return render(request, 'user_log/customer.html', context)
Put a related_name field on your Foreign Key so that other model can refer this model back using realated_name field.
class Entry(models.Model):
cust_name = models.ForeignKey(customer, null= True, on_delete=models.SET_NULL, related_name="entries")
Use your customer object (retrieved using pk) to reach all his entries
customer_objects = customer.objects.get(id=pk_test),
entry_objects = customer_objects.entries.all()
Note: I believe customer_objects is retrieved correctly using pk. Use sigular name customer_object not customer_objects .
I tried to create a new Comment based on these models :
class Answer(models.Model):
answer = models.TextField()
author = models.ForeignKey(CustomUser, on_delete = models.CASCADE,
related_name="written_answers")
question = models.ForeignKey(Question, on_delete = models.CASCADE, related_name="answers")
upvoters = models.ManyToManyField(CustomUser, related_name="upvoted_answers")
created_at = models.DateTimeField(auto_now_add = True, blank = True)
updated_at = models.DateTimeField(blank = True, null=True)
def __str__(self):
return str(self.id)
class Comment(models.Model):
comment = models.CharField(max_length = 200)
author = models.ForeignKey(CustomUser, on_delete = models.CASCADE,
related_name = "written_comments")
answer = models.ForeignKey(Answer, on_delete = models.CASCADE, related_name="comments")
upvoters = models.ManyToManyField(CustomUser, related_name="upvoted_comments")
parent_comment = models.ForeignKey("self", on_delete = models.CASCADE,
related_name="next_in_thread", null=True, blank=False)
created_at = models.DateTimeField(auto_now_add = True, blank = True)
updated_at = models.DateTimeField(null=True, blank = True)
class Meta:
ordering = ('created_at', )
But I get the following error : no such table : main.core_answer__old
What did I do wrong? I tried to delete the SQLite table and the migrations and start over, but this error still persists. Please help.
Edit :
I'm using a populating script after migrating, which creates Questions and Answers, if that makes a difference.
core/models.py
from django.db import models
from users.models import CustomUser
class Genre(models.Model):
name = models.CharField(max_length=84)
subscribers = models.ManyToManyField(CustomUser, related_name="subscribed_genres")
def __str__(self):
return self.name
class Topic(models.Model):
name = models.CharField(max_length=84)
followers = models.ManyToManyField(CustomUser, related_name="followed_topics")
def __str__(self):
return "#" + self.name
class Question(models.Model):
question = models.CharField(max_length = 128, blank = False)
asker = models.ForeignKey(CustomUser, on_delete = models.CASCADE,
related_name="asked_questions")
requested = models.ManyToManyField(CustomUser, related_name="answer_requests")
genres = models.ManyToManyField(Genre, related_name = "questions")
followers = models.ManyToManyField(CustomUser, related_name="followed_questions")
topics = models.ManyToManyField(Topic, related_name="questions")
url = models.CharField(max_length = 150, unique=True)
created_at = models.DateTimeField(auto_now_add = True, blank = True)
updated_at = models.DateTimeField(null=True, blank = True)
class Meta:
ordering = ('-created_at', )
def __str__(self):
return self.question
class Answer(models.Model):
answer = models.TextField()
author = models.ForeignKey(CustomUser, on_delete = models.CASCADE,
related_name="written_answers")
question = models.ForeignKey(Question, on_delete = models.CASCADE, related_name="answers")
upvoters = models.ManyToManyField(CustomUser, related_name="upvoted_answers")
created_at = models.DateTimeField(auto_now_add = True, blank = True)
updated_at = models.DateTimeField(blank = True, null=True)
def __str__(self):
return str(self.id)
class Comment(models.Model):
comment = models.CharField(max_length = 200)
author = models.ForeignKey(CustomUser, on_delete = models.CASCADE,
related_name = "written_comments")
answer = models.ForeignKey(Answer, on_delete = models.CASCADE, related_name="replied_comments")
upvoters = models.ManyToManyField(CustomUser, related_name="upvoted_comments")
parent_comment = models.ForeignKey("self", on_delete = models.CASCADE,
related_name="next_in_thread", null=True, blank=False)
created_at = models.DateTimeField(auto_now_add = True, blank = True)
updated_at = models.DateTimeField(null=True, blank = True)
class Meta:
ordering = ('created_at', )
[RESOLVED] : Upgraded from Django==2.1 to Django==2.2
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)
My models:
class ClientProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, related_name='client_profile')
follows = models.ManyToManyField(User,
related_name='follows',blank=True)
profile_picture = models.ImageField( blank=True)
phone_regex = RegexValidator(
regex=r'^\+?1?\d{9,15}$',
message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed."
)
mobile_number = models.CharField(validators=[phone_regex],
max_length=17, blank=True)
dob = models.DateField(auto_now = False, null = True)
profile_summary = models.TextField()
my_career_objective = models.TextField()
educational_qualification = models.CharField(max_length=200)
work_experience = models.IntegerField(blank=True, null=True)
skill_set = models.TextField(blank=True)
address_1 = models.CharField(max_length=300,blank=True)
address_2 = models.CharField(max_length=300,blank=True)
# new fileds
about_me = models.TextField(blank=True)
birthplace = models.CharField(max_length=150,blank=True)
lives_in = models.CharField(max_length=150,blank=True)
occupation = models.CharField(max_length=150, blank=True)
gender = models.CharField(choices=GENDER_CHOICES,max_length=150, blank=True)
marital_status = models.CharField(choices=MARITAL_CHOICES,max_length=150, blank=True,default=1)
religion = models.CharField(max_length=150, blank=True)
political_incline = models.TextField(blank=True)
# other_social_networks = models.TextField(blank=True)
hobbies = models.TextField(blank=True)
favorite_tv_shows = models.TextField(blank=True)
favorite_movies = models.TextField(blank=True)
favorite_games = models.TextField(blank=True)
favorite_music_band_artists = models.TextField("Favorite Music, Bands / Artists", blank=True)
favorite_books = models.TextField(blank=True)
favorite_writers = models.TextField(blank=True)
other_interests = models.TextField(blank=True)
subscription = models.TextField(blank=True, null=True, default="Free")
def __str__(self):
return str(self.user.first_name) + " " + str(self.user.last_name)
class Task(models.Model):
level = models.ForeignKey(Level, on_delete=models.CASCADE)
todo = models.ForeignKey(ToDo, on_delete=models.CASCADE)
student = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=150)
content = models.TextField()
timestamp = models.TimeField(auto_now=True)
datestamp = models.DateField( auto_now=True)
like = models.ManyToManyField(User,related_name='user_likes',blank=True)
is_verified=models.BooleanField(default=False,blank=True)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('student:dashboard')
objects = PostManager()
#property
def comments(self):
instance = self
qs = Comment.objects.filter_by_instance(instance)
return qs
#property
def get_content_type(self):
instance = self
content_type =
ContentType.objects.get_for_model(instance.__class__)
return content_type
I want to display all tasks from logged in user and also all the tasks from all users followed by logged in user.What is the best django query to implement this? the follows field in the ClientProfile model is given as many to many field to depict all users followed by the user.How to write django query with 'or'.Each task points to a user through foreign key 'student' . I want to display all tasks from logged in user and all users followed by logged in user in the homepage
Put a related_name attribute in student field of Task. (let's call it task)
If logged_in_user is your logged in user object then logged_in_user.task would give task of logged_in_user and for user's followers tasks:
tasks = Task.objects.filter(student__in= logged_in_user.follows.all())
Without related_name.
task = Task.objects.filter(Q(student=logged_in_user) | Q(student__in=logged_in_user.follows.all()))
This worked for me :
client=ClientProfile.objects.get(user=request.user)
task = Task.objects.filter
(Q(student=request.user) |
Q(student__in=client.follows.all()))
.order_by('timestamp').prefetch_related('images_set')