Django Postgresql Error in Production (quiz.models.Question.DoesNotExist:) - python

I am creating a quiz application using a guide. My application works perfectly fine in development with both sqlite3 and postgresql databases. But when pushed to production, I am faced with errors using a postgresql database. So I tried using my development sqlite3 database in production to test things out. My sqlite3 database works fine in production, but postgresql does not work in production. Initially, I thought the error is on the views level, but now I am seeing the error coming from the postgresql. Could be errors in my views or models schema. I really can't tell. The corresponding error I get when using a postgresql database in production using a linux server with gunicorn and nginx is here below, and the whole models design and views are here below too. Thanks, I appreciate your time in giving me a suitable answer to my question.
models.py
from django.db import models
import random
from account.models import Profile
from django.urls import reverse
import datetime
from django.utils import timezone
from ckeditor_uploader.fields import RichTextUploadingField
class PublishedBookManager(models.Manager):
def get_queryset(self):
return super(PublishedBookManager, self).get_queryset().filter(publish_book=True)
class Book(models.Model):
name = models.CharField(max_length=120)
description = models.TextField()
created_by = models.ForeignKey(Profile, default=1, null=True, on_delete=models.SET_NULL)
number_of_questions = models.IntegerField()
number_of_sections = models.IntegerField()
time = models.IntegerField(help_text="duration of the quiz in minutes")
required_score_to_pass = models.IntegerField(help_text="required score in %")
start_date = models.DateTimeField(default=timezone.now)
publish_book = models.BooleanField(default=False)
date_created = models.DateTimeField(auto_now_add=True)
last_updated = models.DateTimeField(auto_now=True)
objects = models.Manager()
published = PublishedBookManager()
def __str__(self):
return f"{self.name}"
def get_absolute_url(self):
return reverse('quiz:book-detail-view', args=[self.pk])
class PublishedQuizManager(models.Manager):
def get_queryset(self):
return super(PublishedQuizManager, self).get_queryset().filter(publish_quiz=True)
class Quiz(models.Model):
book = models.ForeignKey(Book, on_delete=models.CASCADE, blank=True, null=True)
name = models.CharField(max_length=120)
description = models.TextField()
created_by = models.ForeignKey(Profile, default=1, null=True, on_delete=models.SET_NULL)
number_of_questions = models.IntegerField()
time = models.IntegerField(help_text="duration of the quiz in minutes")
required_score_to_pass = models.IntegerField(help_text="required score in %")
completed_users = models.ManyToManyField(Profile, blank=True, related_name='completed_users_quiz')
publish_quiz = models.BooleanField(default=False)
start_date = models.DateTimeField(default=timezone.now)
deadline_date = models.DateTimeField(default=timezone.now)
date_created = models.DateTimeField(auto_now_add=True)
last_updated = models.DateTimeField(auto_now=True)
objects = models.Manager()
published = PublishedQuizManager()
def __str__(self):
return f"{self.book.name} = {self.name}"
def get_questions(self):
questions = list(self.question_set.all())
random.shuffle(questions)
return questions[:self.number_of_questions]
class Meta:
verbose_name_plural = 'Quizes'
def get_absolute_url(self):
return reverse('quiz:quiz-view', kwargs={'book_pk': self.book.pk, "pk": self.pk})
class Question(models.Model):
# text = models.TextField()
text = RichTextUploadingField(unique=True)
second_text = models.TextField()
quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE)
date_created = models.DateTimeField(auto_now_add=True)
def __str__(self):
return str(self.text)
def get_answers(self):
return self.answer_set.all()
# def get_absolute_url(self):
# return reverse('quiz:quiz-view', kwargs={'question_pk': self.pk,})
class Answer(models.Model):
text = models.CharField(max_length=255)
correct = models.BooleanField(default=False)
question = models.ForeignKey(Question, on_delete=models.CASCADE)
date_created = models.DateTimeField(auto_now_add=True)
def __str__(self):
return f"question: {self.question.text}, answer: {self.text}, correct: {self.correct}"
class Result(models.Model):
quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE)
user = models.ForeignKey(Profile, on_delete=models.CASCADE)
score = models.FloatField()
date_created = models.DateTimeField(auto_now_add=True)
def __str__(self):
return str(self.pk)
views.py
def save_quiz_view(request, pk, book_pk):
# if request.user in
quiz = Quiz.objects.get(pk=pk)
# Submition of result only occurs if a user is not in the completed users field. If they are already
# in the completed users ManyToMany field, then it won't save. But if not, it will save.
if request.is_ajax() and not request.user.profile in quiz.completed_users.all():
questions = []
data = request.POST
data_ = dict(data.lists())
data_.pop('csrfmiddlewaretoken')
for _k in data_.keys():
if Question.objects.all():
# print('key: ', k)
k = _k
question = Question.objects.get(text=k)
questions.append(question)
user = request.user.profile
quiz = Quiz.objects.get(pk=pk)
if request.user.is_authenticated:
if not user in quiz.completed_users.all():
quiz.completed_users.add(user)
score = 0
multiplier = 100 / quiz.number_of_questions
results = []
correct_answer = None
for q in questions:
a_selected = request.POST.get(q.text)
if a_selected != "":
question_answers = Answer.objects.filter(question=q)
for a in question_answers:
if a_selected == a.text:
if a.correct:
score += 1
correct_answer = a.text
else:
if a.correct:
correct_answer = a.text
results.append({str(q): {'correct_answer': correct_answer, 'answered': a_selected}})
else:
results.append({str(q): 'not answered'})
score_ = score #* multiplier
Result.objects.create(quiz=quiz, user=user, score=score_)
if score_:#>= quiz.required_score_to_pass:
return JsonResponse({'passed': True, 'score': score_, 'results': results})
else:
return JsonResponse({'passed': False, 'score': score_, 'results': results})
Error
django#UniqueAsf2:~/src$ python3 manage.py runserver 0.0.0.0:8000
Watching for file changes with StatReloader
Performing system checks...
System check identified no issues (0 silenced).
October 26, 2021 - 03:57:12
Django version 3.2.8, using settings 'asf.settings'
Starting development server at http://0.0.0.0:8000/
Quit the server with CONTROL-C.
[26/Oct/2021 03:57:18] "GET /quiz/1/1/ HTTP/1.1" 200 8065
Not Found: /quiz/1/1/assets/vendors/boxicons/css/boxicons.min.css
[26/Oct/2021 03:57:18] "GET /quiz/1/1/assets/vendors/boxicons/css/boxicons.min.css HTTP/1.1" 404 5612
[26/Oct/2021 03:57:18] "GET /quiz/1/1/data/ HTTP/1.1" 200 101
Internal Server Error: /quiz/1/1/save/
Traceback (most recent call last):
File "/home/django/.local/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/home/django/.local/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/django/src/quiz/views.py", line 108, in save_quiz_view
question = Question.objects.get(text=_k)
File "/home/django/.local/lib/python3.9/site-packages/django/db/models/manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/home/django/.local/lib/python3.9/site-packages/django/db/models/query.py", line 435, in get
raise self.model.DoesNotExist(
quiz.models.Question.DoesNotExist: Question matching query does not exist.

Your data in Question is not stored in simple text because you are using RichTextUploadingField which converts text into HTML format for handling text fomatting. Because of this you can't directly compare two strings or run search over it.
Try using icontains for checking string in your field. This might not work in all cases so you'll have to handle that accordingly.
questions = Question.objects.filter(text__icontains=k)
for question in questions:
# Handle questions here

Related

Why Am I getting an Integrity Error while uploading csv file to django app?

While uploading a csv file I'm getting an Integrity Error. I have a correctly working QuizApp which has models about Quiz, Questions and Answers. But I've created another app csvs to upload csv file with Questions and Answers. While I'm trying to upload a CSV file I'm getting that error. The file isn't uploaded to the website.
IntegrityError at /something/admin/csvs/csv/add/
null value in column "quiz_id" of relation "csvs_csv" violates not-null constraint
DETAIL: Failing row contains (11, csvs/example_KLOIQJK.csv, 2022-09-15 05:46:25.666689+00, f, null)
csvs.models.py
class Csv(models.Model):
file_name = models.FileField(upload_to="csvs")
uploaded = models.DateTimeField(auto_now_add=True)
activated = models.BooleanField(default=False)
csvs.forms.py
from django import forms
from csvs.models import Csv
class CsvModelForm(forms.ModelForm):
class Meta:
model = Csv
fields = ("file_name",)
csvs.views.py
from django.shortcuts import render
from django.http import HttpResponse
from .forms import CsvModelForm
# Create your views here.
def upload_file_view(request):
form = CsvModelForm(request.POST or None, request.FILES or None)
if form.is_valid():
form.save()
form = CsvModelForm()
return render(request, "csvs/import.html", {"form": form})
quiz.models.py
from django.db import models
from django.contrib.auth import get_user_model
from django.urls import reverse, reverse_lazy
import uuid
class Quiz(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
title = models.CharField(max_length=200)
short_description = models.CharField(max_length=500)
resolution_time = models.PositiveIntegerField(
help_text="Quiz Duration in minutes", default=15
)
number_of_questions = models.PositiveIntegerField(default=1)
author = models.ForeignKey(
get_user_model(),
on_delete=models.CASCADE,
)
is_public = models.BooleanField(default=False)
required_score_to_pass = models.IntegerField(
help_text="Required score in %", default=50
)
def __str__(self):
return f"Quiz title: {self.title}"
def get_absolute_url(self):
return reverse("quiz_detail", args=[str(self.id)])
def get_absolute_url_edit(self):
return reverse("quiz_edit", args=[str(self.id)])
def get_absolute_url_questions_edit(self):
return reverse("quiz_questions_edit", args=[str(self.id)])
def get_absolute_url_delete(self):
return reverse("quiz_delete", args=[str(self.id)])
def get_absolute_url_my_quizes(self):
return reverse("my_quiz")
def get_absolute_url_answer_edit(self):
return reverse("question_answer_edit")
def get_absolute_url_create(self):
return reverse("quiz_create")
def get_absolute_url_play(self):
return reverse("quiz_play", args=[str(self.id)])
class Question(models.Model):
quiz = models.ForeignKey(
Quiz,
on_delete=models.CASCADE,
related_name="questions",
)
content = models.CharField(max_length=255)
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
def __str__(self):
return self.content
class Answer(models.Model):
content = models.CharField(max_length=255)
question = models.ForeignKey(
Question,
on_delete=models.CASCADE,
related_name="answers",
)
is_correct = models.BooleanField(default=False)
def __str__(self):
return self.content
def is_that_correct_answer(self):
return self.is_correct
class Attempt(models.Model):
user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)
quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE)
score = models.SmallIntegerField(default=1)
has_passed = models.BooleanField(default=False)
attempt_date = models.DateTimeField(auto_now_add=True)
Any ideas?
Looks like you haven't uploaded showed whole CSV model or haven't created new migrations, because CSV model should have on more field - quiz. So either run makemigrations to remove quiz from CSV or in your form add quiz to form fields

Django ManytoManyField query does not exist

I've created models for the logic of friend list and friend request. In the FriendRequest I've defined a method which adds User relation to FriendList if accept method is called. However I'm unable to do so because of the error shown below.
I don't understand the error as I'm adding the User in the model.
views.py
friend_request = FriendRequest.objects.get(id=request_id)
if request_option == 'accept':
friend_request.accept()
if request_option == 'decline':
friend_request.decline()
models.py
class FriendList(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="user")
friends = models.ManyToManyField(User, blank=True, related_name="friends")
def add_friend(self, account):
if not account in self.friends.all():
self.friends.add(account)
self.save()
class FriendRequest(models.Model):
sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name="sender")
receiver = models.ForeignKey(User, on_delete=models.CASCADE, related_name="receiver")
is_active = models.BooleanField(blank=False, null=False, default=True)
timestamp = models.DateTimeField(auto_now_add=True)
def accept(self):
receiver_friend_list = FriendList.objects.get(user=self.receiver)
if receiver_friend_list:
receiver_friend_list.add_friend(self.sender)
sender_friend_list = FriendList.objects.get(user=self.sender)
if sender_friend_list:
sender_friend_list.add_friend(self.receiver)
self.is_active = False
self.save()
def decline(self):
self.is_active = False
self.save()
File "C:\Users\models.py", line 77, in accept
receiver_friend_list = FriendList.objects.get(user=self.receiver)
File "C:\Python310\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Python310\lib\site-packages\django\db\models\query.py", line 496, in get
raise self.model.DoesNotExist(
friends.models.FriendList.DoesNotExist: FriendList matching query does not exist.
You are querying for a non-existing object. To avoid that error use get_or_create:
def accept(self):
receiver_friend_list, created = FriendList.objects.get_or_create(user=self.receiver)
if receiver_friend_list:
receiver_friend_list.add_friend(self.sender)
sender_friend_list = FriendList.objects.get(user=self.sender)
if sender_friend_list:
sender_friend_list.add_friend(self.receiver)
self.is_active = False
self.save()
This is what Django Docs shows and there is a pythonic way also taken from Django Docs.
try:
receiver_friend_list= FriendList.objects.get(user=self.receiver)
except FriendList.DoesNotExist:
receiver_friend_list = FriendList(user=self.receiver)
receiver_friend_list.save()

How to solve url parameter problem in Django?

I have a strange problem.
I have a page that uses url parameters. Users can reach this site based on their project id and name and the group(csoport) name that stored in three models. This is a link for an example page:
/performance/monthlyfeedback/{{ request.user.profile.csoport }}
That link works fine if the name of the csoport is a number. If it is any kind of a text it gives me 404 error that I can't figure out why.
models.py
class Profile(models.Model):
def __str__(self):
return str(self.user)
user = models.OneToOneField(User, null=True, on_delete=models.CASCADE)
csoport = models.CharField(max_length=100, null=True, blank=True)
class Projekt_perf(models.Model):
def __str__(self):
return str(self.projekt_perf)
projekt_perf = models.CharField(max_length=250)
jogosult_01_perf = models.ForeignKey(User, on_delete=models.CASCADE)
date = models.DateField(auto_now_add=True, auto_now=False, blank=True)
class Performance_profile(models.Model):
def __str__(self):
return str(self.user_name)
user_name = models.ForeignKey(User, on_delete=models.CASCADE)
projekt_perf = models.ForeignKey(Projekt_perf,on_delete=models.CASCADE)
views.py
I am using raw query in the views.
def obj_results(request, projekt_perf_id, projekt_perf, user_name_id, csoport):
person = Projekt_perf.objects.raw('SELECT * FROM performance_projekt_perf INNER JOIN performance_performance_profile ON performance_projekt_perf.id = performance_performance_profile.projekt_perf_id INNER JOIN stressz_profile ON performance_performance_profile.user_name_id = stressz_profile.user_id WHERE performance_projekt_perf.id = %s AND projekt_perf = %s AND stressz_profile.user_name_id = %s AND stressz_profile.csoport = %s',[projekt_perf_id, projekt_perf, user_name_id, csoport])
context = {
'person': person,
}
return render(request, 'performance/obj-results.html', context)
urls.py
app_name = 'performance'
urlpatterns = [
path('monthlyfeedback/<int:projekt_perf_id>', login_required(views.Performance_test), name='performance_feedback'),
path('list/<int:projekt_perf_id>/<projekt_perf>', login_required(views.list), name='performance_list'),
path('obj-results/<int:projekt_perf_id>/<projekt_perf>/<int:user_name_id>/<csoport>', login_required(views.obj_results), name='obj_results'),
]
What am I doing wrong?
In urls.py:
path('monthlyfeedback/<int:projekt_perf_id>'
You have defined the “project_perf_id” as int. Change it.
Can you try with <str:csoport> but I reccomend you to use slugs.
path('obj-results/<int:projekt_perf_id>/<projekt_perf>/<int:user_name_id>/<str:csoport>', login_required(views.obj_results), name='obj_results'),

Cannot make the views counter

I'm Trying to create a Views Counter in my django blog. Their are 3 apps in the project. The views counter on the writings app works fine but on the blog app it throws an error 'NoneType' object has no attribute 'views' and shows the error at post.views+=1. However the same code works in the writings app. I cannot find where the problem lies. Maybe the code is returning a empty set that's why it's not working but if so then why the code works when I remove just this views counter code?
Here are the code snippets for Blog and Writings app.
Blog app Views.py:-
post = Post.objects.filter(slug=slug).first()
post.views +=1
post.save()
tech = Tech.objects.filter(slug=slug).first()
tech.views +=1
tech.save()
pcomments = BlogComment.objects.filter(post=post,parent=None)
preplies = BlogComment.objects.filter(post=post).exclude(parent=None)
#Creating Reply Dictionary and iterating it
preplyDict = {}
for reply in preplies:
if reply.parent.sno not in preplyDict.keys():
preplyDict[reply.parent.sno] = [reply]
else:
preplyDict[reply.parent.sno].append(reply)
tcomments = BlogComment.objects.filter(tech=tech,parent=None)
treplies = BlogComment.objects.filter(tech=tech).exclude(parent=None)
#Creating Reply Dictionary and iterating it
treplyDict = {}
for reply in treplies:
if reply.parent.sno not in treplyDict.keys():
treplyDict[reply.parent.sno] = [reply]
else:
treplyDict[reply.parent.sno].append(reply)
context = {'post': post,'tech': tech,'pcomments':pcomments,'tcomments':tcomments,'preplyDict':preplyDict,'treplyDict':treplyDict}
return render(request,'blog/blogPost.html',context)
Writings views.py:-
def wPost(request,slug):
w = Writing.objects.filter(slug=slug).first()
w.views = w.views+1
w.save()
comments = WComment.objects.filter(wpost=w, parent=None)
replies = WComment.objects.filter(wpost=w).exclude(parent=None)
#Creating Reply Dictionary and iterating it
replyDict = {}
for reply in replies:
if reply.parent.sno not in replyDict.keys():
replyDict[reply.parent.sno] = [reply]
else:
replyDict[reply.parent.sno].append(reply)
context = {'writings': w,'comments': comments,'user' : request.user,'replyDict' : replyDict}
return render(request,'writings/wPost.html', context)
Blog Models.py:-
class Post(models.Model):
sno= models.AutoField(primary_key=True)
title = models.CharField(max_length=200)
content = models.TextField()
views = models.IntegerField(default=0)
category = models.CharField(max_length=13)
author = models.CharField(max_length=100)
slug = models.CharField(max_length=150,default=" ")
timeStamp = models.DateTimeField(blank=True)
img = models.ImageField(upload_to="blog/", blank=True)
img2 = models.ImageField(upload_to="blog/", blank=True)
img3 = models.ImageField(upload_to="blog/", blank=True)
img4 = models.ImageField(upload_to="blog/", blank=True)
img5 = models.ImageField(upload_to="blog/", blank=True)
img6 = models.ImageField(upload_to="blog/", blank=True)
def __str__(self):
return self.title + ' by ' + self.author
class Tech(models.Model):
sno= models.AutoField(primary_key=True)
title = models.CharField(max_length=200)
content = models.TextField()
views = models.IntegerField(default=0)
category = models.CharField(max_length=13)
author = models.CharField(max_length=100)
slug = models.CharField(max_length=150,default=" ")
timeStamp = models.DateTimeField(blank=True)
img = models.ImageField(upload_to="blog/", blank=True)
def __str__(self):
return self.title + ' by ' + self.author
Writing Models.py
class Writing(models.Model):
sno= models.AutoField(primary_key=True)
title = models.CharField(max_length=200)
content = models.TextField()
views = models.IntegerField(default=0)
category = models.CharField(max_length=13)
author = models.CharField(max_length=100)
slug = models.CharField(max_length=150,default=" ")
timeStamp = models.DateTimeField(blank=True)
img = models.ImageField(upload_to="writings/", blank=True)
def __str__(self):
return self.title + ' by ' + self.author
Blog admin.py:-
admin.site.register(BlogComment)
#Add this media to the post while registering it.
#admin.register(Post)
class PostAdmin(admin.ModelAdmin):
class Media:
js = ("tinyinject.js",)
#admin.register(Tech)
class TechAdmin(admin.ModelAdmin):
class Media:
js = ("tinyinject.js",)
Writings admin.py:-
admin.site.register(WComment)
#admin.register(Writing)
class WriteAdmin(admin.ModelAdmin):
class Media:
js = ("tinyinject.js",)
Error Starctrace:-
None
Internal Server Error: /blog/learning-python
Traceback (most recent call last):
File "/home/skyrunner/django_blog/mendlife/blogenv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/home/skyrunner/django_blog/mendlife/blogenv/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/skyrunner/django_blog/mendlife/blogenv/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/skyrunner/django_blog/mendlife/blog/views.py", line 18, in blogPost
post.views+=1
AttributeError: 'NoneType' object has no attribute 'views'
So after wasting hours I realised i made a very silly mistake there. As I'm using two models I just simply had to use an If statement. so I added this and it worked as desired
if post is None:
tech.views +=1
tech.save()
else:
post.views+=1
post.save()
Thank you for everybody's comments and feedbacks!

How to add new data from ebay to database in Django?

I am using python ebay-sdk library for connection to ebay api.
I want to get some cases from ebay api and save it to the database.
I have one app and models like this:
class Case(models.Model):
# case is not necessarily a listing (often O2M)
STATUS = Choices('new', 'cancelled', 'active', 'taken_down', 'archived')
name = models.CharField(max_length=512)
when_created = models.DateTimeField(default=now, blank=True)
user = models.ForeignKey(User)
make = models.ForeignKey(Make)
status = StatusField(default=STATUS.new)
platform = models.ForeignKey(Platform, on_delete=models.CASCADE)
listing_id = models.CharField(max_length=64)
listing_owner = models.CharField(max_length=128)
url = models.CharField(max_length=512)
price = models.FloatField(blank=True, null=True)
# for now currency as char is ok.
currency = models.CharField(max_length=3, default='USD')
quantity = models.IntegerField(default=1)
when_listing_started = models.DateTimeField(blank=True, null=True)
when_listing_ends = models.DateTimeField(blank=True, null=True)
valid_days = models.IntegerField(blank=True, null=True)
objects = models.Manager.from_queryset(CaseQueryset)()
def __str__(self):
return self.name
#property
def days_valid(self):
created = self.when_created.replace(tzinfo=None)
now = datetime.datetime.utcnow().replace(tzinfo=None)
datetime.timedelta(6, 1)
return (now - created).days
def handle_sent_report(self):
self._set_active_state()
def handle_cancel(self):
self._set_cancelled_state()
def _set_active_state(self):
if self.status != Case.STATUS.new:
raise InvalidCaseStatus
self.status = Case.STATUS.active
self.save()
def _set_cancelled_state(self):
if self.status not in (Case.STATUS.new, Case.STATUS.active):
raise InvalidCaseStatus
self.status = Case.STATUS.cancelled
self.save()
And I created other app ebay-finder and ebay_find.py to find cars in eBay:
from ebaysdk.finding import Connection as Finding
from django.db import models
from cases.models import Case
from trademarks.models import Make
def ebay_find():
pass
api = Finding(domain='svcs.sandbox.ebay.com', appid="MY_EBAY_APP_ID", config_file=None)
response = api.execute('findItemsAdvanced', {'keywords': 'Cadillac'})
items = response.dict()
items_list = items['searchResult'].get('item')
ebay_cases = []
for item in items_list:
new_case = Case.objects.create(
name=item['title'],
platform="Ebay",
listing_id=car["model"],
url=item['viewItemURL'],
price=item['sellingStatus']['currentPrice']['value'],
currency=item['sellingStatus']['currentPrice']['_currencyId']
)
new_case.save()
I'm confused how to add this data from items_list to my database like in Case. I must take all the same fields like in Case? Can I have some fields default on create object?
If your want your data to be saved with the least hassle, then yes, use the same field-names.
You have an example of a model field with a default in your own code:
currency = models.CharField(max_length=3, default='USD')
You could also override your model's save() method:
def save(self, *args, **kwargs):
super(Case, self).save(*args, **kwargs)
if not self.when_listing_started:
self.when_listing_started = datetime.datetime.now()
super(Case, self).save(*args, **kwargs)

Categories

Resources