insert json data into MySQL database - django

1.I want to save data from database(mysql) to .json file format.
Models.py
class Author(models.Model):
author_id = models.AutoField(primary_key=True)
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=40)
email = models.EmailField()
age=models.IntegerField()
class Meta:
db_table=u'Author'
def __unicode__(self):
return u"%d %s %s %s %d" % (self.pk, self.first_name, self.last_name, self.email,self.age)
class Book(models.Model):
book_id=models.AutoField(primary_key=True,unique=True)
book_name=models.CharField(max_length=30)
publisher_name=models.CharField(max_length=40)
author=models.ForeignKey(Author)
class Meta:
db_table = u'Book'
def __unicode__(self):
return u'%d %s %s' % (self.pk, self.book_name, self.publisher_name)
views.py is
def addbook(request):
log.debug("test....")
if request.POST:
first_name = request.POST.get('first_name')
last_name = request.POST.get('last_name')
email = request.POST.get('email')
age = request.POST.get('age')
author = Author(first_name = first_name,last_name = last_name,email=email,age=age)
author.save()
book_name = request.POST.get('book_name')
publisher_name = request.POST.get('publisher_name')
author_info = Author.objects.latest('author_id')
log.debug("test:%s",author_info.author_id)
book=Book(book_name=book_name,publisher_name=publisher_name,author_id=author_info.author_id)
book.save()
return redirect('/index/')
else:
return render_to_response('addbook.html',context_instance=RequestContext(request))
1) In views.py an addbook function is used to add the related data to database.
2) I have to store the database content to a json file after each entry.
3) Can i get help to code the same.

This link explains how to serialize Django models. You will have to add something like this to your model code:
from django.core import serializers
class Book(models.Model):
...
def serialize(self):
JSONSerializer = serializers.get_serializer("json")
json_serializer = JSONSerializer()
with open("/path/to/file/file.json", "w") as out:
json_serializer.serialize([self], stream=out)
The square brackets around [self] are important if you want to serialize a particular instance of a model. If you are serializing a queryset then you can pass that in instead.

Related

Django REST framework. How i can make export model in csv

I have the following models:
class Student(models.Model):
first_name = models.CharField(verbose_name='student first name', max_length=64)
last_name = models.CharField(verbose_name='student last name', max_length=64)
email = models.EmailField()
class Meta:
db_table = 'student'
def __str__(self):
return self.first_name + ' ' + self.last_name
class Course(models.Model):
name = models.CharField(max_length=255)
description = models.TextField()
start_date = models.DateField(null=True, blank=True, default=None)
end_date = models.DateField(null=True, blank=True, default=None)
class Meta:
db_table = 'course'
def __str__(self):
return self.name
class CourseParticipant(models.Model):
course = models.ForeignKey(Course, related_name='courses', on_delete=models.CASCADE)
student = models.ForeignKey(Student, related_name='student_name', on_delete=models.CASCADE)
completed = models.BooleanField(null=False, default=False)
class Meta:
db_table = 'course_participant'
def __str__(self):
return self.course, self.student
And urs:
urlpatterns = [
path('course', CourseAPIView.as_view()),
path('course/<int:pk>/', CourseAPIDetailView.as_view()),
path('student', StudentAPIView.as_view()),
path('student/<int:pk>/', StudentAPIDetailView.as_view()),
path('student/assigned_to_course', StudentAssignedToTheCourseAPIView.as_view()),
path('student/assign_student_to_course', StudentAssignToCourse.as_view()),
path('student/assigned_to_course/<int:pk>/', StudentAssignedToTheCourseDetailView.as_view()),
path('student/report/<int:pk>/', StudentReportView.as_view()),
]
I need made export some data in csv, in next format:
student full name
number of assigned courses to the student
number of completed courses by student
For example:
Test Student,10, 3
Test Student1,12, 1
Test Student2,5, 3
Test Student3,5, 4
So, what view should be for it. I mean, how i can get data like student full name and etc. I will be grateful for the help
You can use Python's csv module.
At first, I would suggest defining full_name as a property in your Student model since it will make it clearer:
class Student(models.Model):
...
#property
def full_name(self):
return self.first_name + ' ' + self.last_name
Then you can define a simple APIView for the job:
import csv
from django.http import HttpResponse
from rest_framework.views import APIView
class ExportCSVStudents(APIView):
def get(self, request, *args, **kwargs):
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="export.csv"'
writer = csv.writer(response)
for student in Student.objects.all():
assigned_courses = CourseParticipant.objects.filter(student=student)
completed_courses = assigned_courses.filter(completed=True)
row = ','.join([
student.full_name,
assigned_courses.count(),
completed_courses.count()
])
writer.writerow(row)
return response
This should automatically download a file called export.csv with your desired data, after you register it in your urlconf and access it via simple HTTP GET.

Display full names in Form ChoiceField but saving ID's

I have model Person - from another database
I copied all person_id to custom_id.
models.py
class Employee(models.Model):
custom_id = models.CharField(max_length=20, unique=True)
#property
def person(self):
return Person.objects.get(person_id='%s' % self.custom_id)
def __str__(self):
return '%s' % self.custom_id
class Task(models.Model):
employee = models.ManyToManyField(Employee, blank=True, null=True)
task = models.CharField(max_length=100)
comment = models.CharField(max_length=200)
def __str__(self):
return '%s' % self.task
I add my method person() to Employee which allow me to access other objects model in another database:
So basically when I type this in shell:
Employee.objects.get(custom_id='123').person.full_name
u'Adam Dylan'
I have a ModelForm which use ModelMultipleChoiceField
forms.py
class TaskCreateForm(forms.ModelForm):
employee = forms.ModelMultipleChoiceField(queryset=Employee.objects.all())
class Meta:
model = Task
But Employee.objects.all() returns bunch of custom_id's.
What I want is to show in form "Employee(..).person.full_name" but saving only custom_id's.
I am not sure why you think the answer I gave to your other question does not work here. Did you try the following? If it does not work, how exactly does it fail?
class EmployeeMultipleChoiceField(ModelMultipleChoiceField):
def label_from_instance(self, obj):
return obj.person.full_name
class TaskCreateForm(forms.ModelForm):
employee = EmployeeMultipleChoiceField(queryset=Employee.objects.all())
class Meta:
model = Task

display foreignkey field in django template

I have models.py like below:
class Profile(models.Model):
user = models.OneToOneField(User)
def __unicode__(self):
return "%s" % self.user
class Student(models.Model):
user = models.ForeignKey(Profile)
phone_num = models.CharField(max_length=15)
def __unicode__(self):
return "%s" % (self.user)
class Teacher(models.Model):
user = models.ForeignKey(Profile)
phone_num = models.CharField(max_length=15)
def __unicode__(self):
return "%s" % (self.user)
class Complaint(models.Model):
user = models.ForeignKey(Student)
complaint = models.TextField()
teacher = models.ForeignKey(Teacher, null=True)
def __unicode__(self):
return "%s : %s" % (self.complaint)
How can I display teacher's name which is eventually stored in class Profile
What I get is a column teacher_id in _complaint table when I do
student_obj = Student.objects.get(name=user_profile_instance)
and then
compaint = student_obj.complaint_set.values()
in complaint.html
{{complaint.teacher_id}}
what I want is teacher name instead of id
This should work -
{{ complaint.teacher.user.user.first_name }}
First of all Please Update your style of coding to make your App Optimised
Use
student_obj = Student.objects.select_related().get(name=user_profile_instance)
The Above one will Cache Datas . After that each time when u call Datas from fields it Wont HIT your database :) , Hence Your App will Fly
instead of
student_obj = Student.objects.get(name=user_profile_instance)
and i'm Agreeing with #Bibhas Answer
{{ complaint.teacher.user.user.first_name }}
Teacher's Profile is Inheriting Django's Auth Model User
That wise
user.user.first_name

TypeError, 'Class object' object is not subscriptable

I'm trying to add an "event" in the admin and get this error:
TypeError at /admin/sms/event/add/
'Contact' object is not subscriptable
models.py:
class Contact(models.Model):
users = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="contact")
name = models.CharField(_("Recipient"), max_length=40)
phone = models.IntegerField(_("Phone"), max_length=10)
def __unicode__(self):
return "%s: %d" % (self.name, self.phone)
class Event(models.Model):
calendar = models.ForeignKey(Calendar, verbose_name=_("Calendar"), related_name="event_calendar")
message = models.ForeignKey(Message, verbose_name=_("Message"), related_name="event_message")
recipient = models.ForeignKey(Contact, verbose_name=_("Recipient"), related_name="event1")
event_date = models.DateField(_("Date"))
start_time = models.TimeField(_("Start time"))
end_time = models.TimeField(_("End time"), blank=True, null=True)
location = models.CharField(_("Location of meeting"), blank=True, null=True, max_length=100)
reminder_options = models.IntegerField(choices=ReminderOptions.CHOICES, verbose_name=_("Reminder time"))
content = models.CharField(_("Event Notes"), max_length=160)
# recurring_options = models.IntegerField(choices=RecurringOptions.CHOICES, verbose_name=_("Recurring time"))
def __unicode__(self):
return self.recipient
def get_absolute_url(self):
return u'/create-event/'
First guess is that your phone field gets a string from your admin form. Use a charField for phone in your model and make a custom form in your admin.py.
In models.py change your phone Integerfield to a CharField:
class Contact(models.Model):
...
phone = models.CharField(_("Phone"), max_length=200)
def __unicode__(self):
return "%s: %s" % (self.name, self.phone) # %d becomes %s
In Admin.py create a form:
from models import Contact
from django import forms
from django_localflavor_fr.forms import FRPhoneNumberField
class ContactForm(forms.ModelForm):
phone = FRPhoneNumberField()
class Meta:
model = Contact
https://docs.djangoproject.com/en/1.5/ref/contrib/localflavor/
In Admin.py create a ModelAdmin:
class ContactAdmin(admin.ModelAdmin):
form = ContactForm

django-piston: how to get values of a many to many field?

I have a model with ManyToManyField to another model. I would like to get all the info on a particular record (including the related info from other models) return by JSON.
How to get django-piston to display those values? I would be happy with just primary keys.
Or can you suggest another option ?
I may be wrong, but this should do it:
class PersonHandler(BaseHandler):
model = Person
fields = ('id', ('friends', ('id', 'name')), 'name')
def read(self, request):
return Person.objects.filter(...)
You need to define a classmethod on the handler that returns the many-to-many data, I don't believe Piston does this automatically.
class MyHandler(BaseHandler):
model = MyModel
fields = ('myfield', 'mymanytomanyfield')
#classmethod
def mymanytomanyfield(cls, myinstance):
return myinstance.mymanytomanyfield.all()
My code:
Models:
class Tag(models.Model):
"""docstring for Tags"""
tag_name = models.CharField(max_length=20, blank=True)
create_time = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return self.tag_name
class Author(models.Model):
"""docstring for Author"""
name = models.CharField(max_length=30)
email = models.EmailField(blank=True)
website = models.URLField(blank=True)
def __unicode__(self):
return u'%s' % (self.name)
class Blog(models.Model):
"""docstring for Blogs"""
caption = models.CharField(max_length=50)
author = models.ForeignKey(Author)
tags = models.ManyToManyField(Tag, blank=True)
content = models.TextField()
publish_time = models.DateTimeField(auto_now_add=True)
update_time = models.DateTimeField(auto_now=True)
def __unicode__(self):
return u'%s %s %s' % (self.caption, self.author, self.publish_time)
Handle:
class BlogAndTagsHandler(BaseHandler):
allowed_methods = ('GET',)
model = Blog
fields = ('id' 'caption', 'author',('tags',('id', 'tag_name')), 'content', 'publish_time', 'update_time')
def read(self, request, _id=None):
"""
Returns a single post if `blogpost_id` is given,
otherwise a subset.
"""
base = Blog.objects
if _id:
return base.get(id=_id)
else:
return base.all() # Or base.filter(...)
Works petty good.