<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Rugved</title>
    <description>The latest articles on DEV Community by Rugved (@rugved).</description>
    <link>https://dev.to/rugved</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F626405%2F3c0e2cf6-8ebe-4c6c-a40c-756a011978bf.jpeg</url>
      <title>DEV Community: Rugved</title>
      <link>https://dev.to/rugved</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/rugved"/>
    <language>en</language>
    <item>
      <title>Admits and Rejects | MS in US | Fall 2022</title>
      <dc:creator>Rugved</dc:creator>
      <pubDate>Tue, 26 Jul 2022 04:09:22 +0000</pubDate>
      <link>https://dev.to/rugved/admits-and-rejects-ms-in-us-fall-2022-26de</link>
      <guid>https://dev.to/rugved/admits-and-rejects-ms-in-us-fall-2022-26de</guid>
      <description>&lt;p&gt;&lt;iframe width="710" height="399" src="https://www.youtube.com/embed/JnVZQwiQC7Q"&gt;
&lt;/iframe&gt;
&lt;/p&gt;

</description>
    </item>
    <item>
      <title>How to convert database model to csv,xls,json etc and vice versa using django-import-export?</title>
      <dc:creator>Rugved</dc:creator>
      <pubDate>Fri, 14 May 2021 07:36:42 +0000</pubDate>
      <link>https://dev.to/rugved/how-to-convert-database-model-to-csv-xls-json-etc-and-vice-versa-using-django-import-export-41pa</link>
      <guid>https://dev.to/rugved/how-to-convert-database-model-to-csv-xls-json-etc-and-vice-versa-using-django-import-export-41pa</guid>
      <description>&lt;h2&gt;
  
  
  Introduction
&lt;/h2&gt;

&lt;p&gt;In this blog we are going to use an amazing library django-import-export which can convert database to various formats like csv, xls, json, html, yaml, tsv, ods. It can do it the other way round too which means that it can convert a file to database and it does it very smarty. Read the blogtill the end and you will know why i said smartly!&lt;/p&gt;

&lt;h2&gt;
  
  
  Prerequisites
&lt;/h2&gt;

&lt;p&gt;Django installed&lt;/p&gt;

&lt;h2&gt;
  
  
  What are we building?
&lt;/h2&gt;

&lt;p&gt;In this blog we will go from very simple example covering char field,Foreign Key,Many to Many field and learn how to convert import and export data into csv.&lt;/p&gt;

&lt;h2&gt;
  
  
  Setup
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;Open cmd.&lt;/li&gt;
&lt;li&gt;Create a django project and cd into it.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;django-admin startproject DemoProject 
cd DemoProject
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Create a django app.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;django-admin startapp app
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This is how you project structure should look like until now.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fmiro.medium.com%2Fmax%2F296%2F1%2AHfbZPyG49pFgymXwvW-96A.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fmiro.medium.com%2Fmax%2F296%2F1%2AHfbZPyG49pFgymXwvW-96A.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;*&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;pip install django-import-export package
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Go to settings.py and add “app” (app name) and “import_export” (django-import-export) to list of “INSTALLED_APPS” as shown below.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'import_export', # Added by us
    'app', # Add the app name you created
]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  Creating Models
&lt;/h2&gt;

&lt;p&gt;Lets create a few models and perform all required actions over it to easily understand how django-import-export library works.&lt;/p&gt;

&lt;h3&gt;
  
  
  Models:
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;Book&lt;/li&gt;
&lt;li&gt;Category — category to which a book belongs&lt;/li&gt;
&lt;li&gt;Author — Author of a book&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Book model’s fields and relations:
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;name — char field representing name of book.&lt;/li&gt;
&lt;li&gt;author — Foreign key to Author model representing author of book.&lt;/li&gt;
&lt;li&gt;categories — ManyToMany field to Category model representing to which single/multiple categories book belongs.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Open models.py inside app folder and add following code.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# app/models.py

from django.db import models

class Category(models.Model):
    name = models.CharField(max_length=100)

    def __str__(self):
        return self.name

class Author(models.Model):
    name = models.CharField(max_length=100)

    def __str__(self):
        return self.name

class Book(models.Model):
    name = models.CharField(max_length=100)
    author = models.ForeignKey(Author,on_delete = models.CASCADE ,blank=True, null=True)
    categories = models.ManyToManyField(Category, blank=True)

    def __str__(self):
        return self.name
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now run the following command. We do this to create a file in migrations folder which keeps tracks of how database schema is altered. In our case we just added new models.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;python manage.py makemigrations
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fjmufrdpvkd5u68iaktuh.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fjmufrdpvkd5u68iaktuh.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Until now we have just noted the alterations on database schema but now we will run a command to apply the changes mentioned in migrations file to actual database (default sqlite). Also you will see User model’s migrations too which is present by default.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;python manage.py migrate
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4tqyke5y1yb623w0wqfc.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F4tqyke5y1yb623w0wqfc.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;That’s it for database for now. Now lets create a superuser so that we can use django admin. Enter username,mail,password of your choice. We will require this credentials later to access admin page.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;python manage.py createsuperuser
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fajysb1c9sxthp67v5iiu.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fajysb1c9sxthp67v5iiu.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Before moving to admin page one last thing we need to do is tell django that these are our models and we want to access it on django admin page. To do this we need to register models in “admin.py” file present in apps folder.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;# app/admin.py
from django.contrib import admin
from .models import *

@admin.register(Book)
class BookAdmin(admin.ModelAdmin):
    pass

@admin.register(Author)
class AuthorAdmin(admin.ModelAdmin):
    pass

@admin.register(Category)
class CategoryAdmin(admin.ModelAdmin):
    pass
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;All basic set up id done. Lets run the server now.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;python manage.py runserver
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Go to &lt;a href="http://127.0.0.1:8000/admin/" rel="noopener noreferrer"&gt;http://127.0.0.1:8000/admin/&lt;/a&gt; . You should be able to see all the models we registered in admin.py&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F142py173kp5nkif6qs02.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F142py173kp5nkif6qs02.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Lets create dummy data. You can do it manually but i have got a easier solution.Create a file “myscript.py” in the root directory (along side manage.py) as shown below.&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fh8beyii37s8w48olmsof.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fh8beyii37s8w48olmsof.png" alt="image"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Paste the following code into “myscript.py” and run it.&lt;br&gt;
Basically this code will do the following-&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Create 100 Category instances with random names.&lt;/li&gt;
&lt;li&gt;Create 5 Author instances with random names.&lt;/li&gt;
&lt;li&gt;Create 30 Book instances with random names.
&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import os

PROJECT_NAME = 'DemoProject'

def main():
    from app.models import Category,Book,Author
    import uuid
    from random import randrange

    categor_ids = []
    for i in range(100):
        c = Category.objects.create(name = str(i+1) +" - "+uuid.uuid4().hex[:6]+"-categoryname")
        categor_ids.append(c.id)

    author_ids = []
    for i in range(5):
        a = Author.objects.create(name = str(i+1) +" - "+uuid.uuid4().hex[:6]+"-authorname")
        author_ids.append(a.id)

    for i in range(30):
        #  Generate random number between 0 to 4
        author_id = author_ids[randrange(5)]

        book = Book.objects.create(
            name = str(i+1) +" - "+uuid.uuid4().hex[:6]+"-bookname",
            author = Author.objects.get(id = author_id),
        )

        #  Generate random number between 0 to 5 - this will be equal to how many category items should we pick
        num_of_category = randrange(6)

        for i in range(num_of_category):
            book.categories.add(Category.objects.get(id = categor_ids[randrange(100)]))

        book.save()


if __name__ == '__main__':
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', '%s.settings' % PROJECT_NAME)
    import django
    django.setup()
    main()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;python myscript.py
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;After executing and completion of the above command visit &lt;a href="http://127.0.0.1:8000/admin/" rel="noopener noreferrer"&gt;http://127.0.0.1:8000/admin/&lt;/a&gt; and you will see that data is populated already.&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fl6m3wa5cpc4miu8zib1n.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fl6m3wa5cpc4miu8zib1n.png" alt="image"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;b&gt;Well now what? how can we convert this data to csv, json etc??&lt;/b&gt;&lt;br&gt;
We will need to tell django that hey provide me a button to import export data from admin page. To do this we need to modify “admin.py” in apps folder which we earlier created.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from django.contrib import admin
from .models import *
from import_export.admin import ImportExportModelAdmin

@admin.register(Book)
class BookAdmin(ImportExportModelAdmin):
    pass

@admin.register(Author)
class AuthorAdmin(ImportExportModelAdmin):
    pass

@admin.register(Category)
class CategoryAdmin(ImportExportModelAdmin):
    pass
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now visit the admin page &lt;a href="http://127.0.0.1:8000/admin/" rel="noopener noreferrer"&gt;http://127.0.0.1:8000/admin/&lt;/a&gt; and click on Book or Category or Author model. I opened Book model. You will see that import export button at the top right!&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fbl3yg5gokeliguvr9shf.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fbl3yg5gokeliguvr9shf.png" alt="image"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Click on export button. And select any format and click submit. I have selected xls format. A file will get downloaded which will have all your database enteries.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fhzwgi67egafe2thcbivw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fhzwgi67egafe2thcbivw.png" alt="image"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;When it comes to foreign key (author field) we get primary key of author model’s instance and similarly for many to many field (categories) we get comma separated ids of category instance.&lt;/p&gt;

&lt;p&gt;For eg. Row 1 implies book with primary key 30 has author with primary key 4 and has categories whose ids are 2,12,17,32,33.&lt;/p&gt;

&lt;p&gt;Yayy! Look at that! With just a few button clicks now we can convert out entire model data to xls/csv/json etc.&lt;/p&gt;

&lt;h2&gt;
  
  
  Importing data
&lt;/h2&gt;

&lt;p&gt;Now comes interesting part which is importing the data. This package handles it so smartly. Lets see how.&lt;/p&gt;

&lt;p&gt;Lets say in the file i downloaded i do the following changes and save it:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;add one more row (i.e i want to add this row to database)
&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fhdwrgaqhxsisbx4pnhp5.png" alt="image"&gt;
&lt;/li&gt;
&lt;li&gt;add a category id for any one row.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;b&gt;Before:&lt;/b&gt;&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Foaceclolrqi7nt26w4r5.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Foaceclolrqi7nt26w4r5.png" alt="image"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;b&gt;After:&lt;/b&gt;&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fpeno2byecxqabrsxp4wq.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fpeno2byecxqabrsxp4wq.png" alt="image"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Don’t forget to save the changes.&lt;/p&gt;

&lt;p&gt;Now got to &lt;a href="http://127.0.0.1:8000/admin/app/book/" rel="noopener noreferrer"&gt;http://127.0.0.1:8000/admin/app/book/&lt;/a&gt; and click on import and upload the updated file and select proper file format and click submit.&lt;/p&gt;

&lt;p&gt;And you will see that it will automatically detect the changes you made and highlight it with operation name (eg. update,New etc) and on submitting it will apply those changes to database.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fhtnag5b6u2niy476i6yp.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fhtnag5b6u2niy476i6yp.png" alt="image"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Also cross verify that it is actually added to book model and you will see that it has been reflected in database.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fi49do99wiseyj3eo271g.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fi49do99wiseyj3eo271g.png" alt="image"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;That’s all we had to do to convert database to file and vice versa!&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;To know more about the django-import-export package visit &lt;a href="https://django-import-export.readthedocs.io/en/latest/index.html" rel="noopener noreferrer"&gt;https://django-import-export.readthedocs.io/en/latest/index.html&lt;/a&gt;.  &lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion:
&lt;/h2&gt;

&lt;p&gt;We successfully learnt to convert django model’s data to csv,json,xls,yaml etc and the reverse.&lt;/p&gt;

&lt;p&gt;For code you can visit &lt;strong&gt;&lt;a href="https://github.com/RugvedB/django-database-to-files-and-vice-versa" rel="noopener noreferrer"&gt;https://github.com/RugvedB/django-database-to-files-and-vice-versa&lt;/a&gt;&lt;/strong&gt;&lt;/p&gt;

</description>
      <category>django</category>
      <category>webdev</category>
      <category>database</category>
    </item>
    <item>
      <title>Django standalone script to take database backup</title>
      <dc:creator>Rugved</dc:creator>
      <pubDate>Thu, 06 May 2021 06:00:26 +0000</pubDate>
      <link>https://dev.to/rugved/django-standalone-script-to-take-database-backup-2287</link>
      <guid>https://dev.to/rugved/django-standalone-script-to-take-database-backup-2287</guid>
      <description>&lt;p&gt;In this blog we will learn to write standalone script which will be a generalized script to convert entire database to csv/xls files etc.&lt;/p&gt;

&lt;p&gt;Standalone script is basically a script where you don’t need to run server. It is “stand alone” i.e it is capable of performing tasks without any other requirement.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;This blog was initially published on &lt;a href="https://www.gyaanibuddy.com/blog/django-standalone-script-to-take-database-backup/"&gt;https://www.gyaanibuddy.com/blog/django-standalone-script-to-take-database-backup/&lt;/a&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3&gt;
  
  
  Prerequisites
&lt;/h3&gt;

&lt;p&gt;A django project with any database along with some models whose data you wish to take backup.&lt;/p&gt;

&lt;h3&gt;
  
  
  Basic template
&lt;/h3&gt;

&lt;p&gt;This code is going to be the bare minimum skeleton of our script.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Create a script.py file in the same directory as manage.py file.&lt;/li&gt;
&lt;li&gt;Paste the below code snippet.&lt;/li&gt;
&lt;li&gt;Rename PROJECT_NAME to your project’s name
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import os
PROJECT_NAME = 'ENTER YOUR PROJECT NAME HERE'

def main():
    # import statemts
    # from app.models import Author,Category,Book

    # code logic - anything you want


if __name__ == '__main__':
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', '%s.settings' % PROJECT_NAME)
    import django
    django.setup()
    main()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Run the code by entering &lt;code&gt;python script.py&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;If it ran with no errors then you are good to go. If you have any error, then depending on error you may have path error, installed app error etc.&lt;/p&gt;

&lt;h3&gt;
  
  
  Backup script
&lt;/h3&gt;

&lt;p&gt;If you are only interested in the script, scroll to the bottom and just paste it in script.py and run it.&lt;/p&gt;

&lt;p&gt;Lets look at some of the basic functions which will help us get the script ready.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Firstly, we need list of all the models.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from django.apps import apps 
model_list = apps.get_models() 
model_name_list = [x.__name__ for x in model_list]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Now that we have the model, we will iterate over every single table and get its schema i.e the columns (or fields) in the table. We need the field/column names so that we can write them as column names to csv/xls file.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;for model in model_list:
    all_fields = model._meta.get_fields()
    columns = [x.name for x in all_fields]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Lets iterate over entire database and write the data to csv/xls.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;with open(f'csvs/{model.__name__}.csv', mode='w') as csv_file:
  writer = csv.writer(csv_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
  # Writing column names
  writer.writerow(columns)
  objects = model.objects.all()

  for obj in objects:
    row = [str(getattr(obj, field_name,"NA")) for field_name in columns]
    writer.writerow(row)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;You will observe that a csv folder is created and inside it will contain one csv file for every table. So if you have Author, Book as tables, you will have Author.csv and Book.csv saved in the csv folder in the project root directory.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;'''
django standalone script to take backup of database in the form of csvs for each model.
- Place it in the same directory as manage.py file
- Rename PROJECT_NAME to your project's name
'''

import os

PROJECT_NAME = '--- ENTER YOUR PROJECT NAME HERE ---'

def main():
    from django.apps import apps
    import csv

    model_list = apps.get_models()
    model_name_list = [x.__name__ for x in model_list]

    for model in model_list:
        all_fields = model._meta.get_fields()
        columns = [x.name for x in all_fields]

        if not os.path.exists('csvs'):
            os.makedirs('csvs')

        with open(f'csvs/{model.__name__}.csv', mode='w') as csv_file:
            writer = csv.writer(csv_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)

            # Writing column names
            writer.writerow(columns)

            objects = model.objects.all()

            for obj in objects:
                row = [str(getattr(obj, field_name,"NA")) for field_name in columns]
                writer.writerow(row)

if __name__ == '__main__':
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', '%s.settings' % PROJECT_NAME)
    import django
    django.setup()
    main()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Based on your preference you can store the database in any form (Eg. sqlite,xls,csv,json etc). In the above script i have created a “csv” folder and inside it contains individual csv file for each model. Each csv will contain data of one model and will have column name as field names and each row will be single entry of that specific model.&lt;/p&gt;

&lt;p&gt;Yayy! That’s all you need to do to write standalone script in django to take backup of database.&lt;/p&gt;

</description>
      <category>django</category>
      <category>webdev</category>
      <category>databasebackup</category>
      <category>djangostandalonescript</category>
    </item>
  </channel>
</rss>
