Advance Python Chapter 4
Advance Python Chapter 4
[Q-4]
(A)
4. Define model.
➢ A model in Django is a Python class that defines the structure of a
database table.
import mysql.connector
import tkinter as tk
def create_database():
conn = mysql.connector.connect(
host="localhost",
user="root",
password=""
)
cursor = conn.cursor()
cursor.execute("CREATE DATABASE IF NOT EXISTS mydatabase
conn.close()
root.mainloop()
2. Write down the code to create table.
import mysql.connector
import tkinter as tk
def create_table():
conn = mysql.connector.connect(
host="localhost",
user="root",
password="",
database="mydatabase"
)
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
age INT NOT NULL
)
""")
conn.close()
root.mainloop()
3. Write down the code to insert 5 records in the table (table name:
student).
import mysql.connector
import tkinter as tk
def insert_records():
conn = mysql.connector.connect(
host="localhost",
user="root",
password="",
database="mydatabase"
)
cursor = conn.cursor()
# Records to be inserted
records = [
("Alice", 20),
("Bob", 21),
("Charlie", 22),
("David", 23),
("Eve", 20)
]
# Execute query
cursor.executemany(query, records)
conn.commit()
conn.close()
root.mainloop()
4. Write down the code to fetch all data from table.
import mysql.connector
import tkinter as tk
def fetch_data():
conn = mysql.connector.connect(
host="localhost",
user="root",
password="",
database="mydatabase"
)
cursor = conn.cursor()
conn.close()
root.mainloop()
5. Explain get( ) and filter( ) method for update operations.
➢ get() Method:
o The get() method retrieves a single object from the database.
o It is used when we know that only one record matches the
condition.
o After fetching the object, we update its fields and call save().
o If no record is found or multiple records exist, it raises an error.
student = Student.objects.get(id=1)
student.name = "Updated Name"
student.save()
➢ filter() Method:
o he filter() method retrieves a QuerySet (multiple records)
matching the condition.
o We use .update() to modify multiple records at once.
o It does not require calling save() separately.
Student.objects.filter(age=20).update(name="Updated Name")
6. Explain Model class and variable.
➢ In Django, a Model class is used to define the structure of a database
table.
➢ It is created in the models.py file and works with Django’s Object-
Relational Mapping (ORM) to interact with the database.
➢ Allows CRUD operations (Create, Read, Update, Delete) without writing
raw SQL queries.
➢ Provides data validation using built-in field types.
➢ Example:
from django.db import models
class Student(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()
email = models.EmailField(unique=True)
➢ Model Variables:
o Model variables (fields) define the columns of the table.
o Each variable has a data type that specifies the type of data it can
store.
o name Stores student names (text).
o age Stores student ages (numbers).
o email Stores unique student emails.
7. Explain database fields.
➢ In Django, a database field is an attribute of a model that represents a
column in a database table.
➢ Each field is defined using Django's built-in field types in the models.py
file.
➢ Example:
from django.db import models
class Student(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()
email = models.EmailField(unique=True)
admission_date = models.DateField()
➢ Text Fields:
o CharField(max_length=100): Stores short text (e.g., names).
o TextField(): Stores long text (e.g., descriptions).
➢ Number Fields:
o IntegerField(): Stores whole numbers.
o FloatField(): Stores decimal numbers.
➢ Boolean Field:
o BooleanField(): Stores True or False values.
➢ Date and Time Fields:
o DateField(): Stores a date.
o DateTimeField(): Stores date and time.
➢ Other Fields:
o EmailField(): Stores emails.
o URLField(): Stores website URLs.
(C)
1. Write down the code to display records from the student table on the
base of the name field.
import mysql.connector
import tkinter as tk
from tkinter import messagebox
# Database Connection
conn = mysql.connector.connect(
host="localhost",
user="root",
password="",
database="mydatabase"
)
cursor = conn.cursor()
# Display results
if records:
for record in records:
text_display.insert(tk.END, f"ID: {record[0]}, Name:
{record[1]}, Age: {record[2]}\n")
# Tkinter GUI
root = tk.Tk()
root.title("Fetch Student Records")
root.mainloop()
2. Write down the code to update any three records on the base of the
name field and display all the records.
import mysql.connector
import tkinter as tk
# Tkinter GUI
root = tk.Tk()
root.title("User Records")
root.mainloop()
conn.close()
3. Write down the code to access data from emp table those who earn
salary more than average salary. Table Name emp Columns empno,
ename, deptno, salary
import mysql.connector
import tkinter as tk
# Tkinter GUI
root = tk.Tk()
root.title("Employees with Salary > Avg Salary")
root.mainloop()
conn.close()
4. Explain database defining Model in Python.
➢ A database model in Python is a structured representation of a database
table using Object-Relational Mapping (ORM).
➢ Instead of writing raw SQL queries, Python classes define how data is
stored, retrieved, and manipulated.
➢ Using ORM provides:
o Better Code Readability – No need to write complex SQL queries.
o Security – Protects against SQL injection.
o Portability – Works with multiple database systems (e.g., SQLite,
MySQL, PostgreSQL).
➢ Popular ORMs in Python include:
o Django ORM – Used in Django framework.
o SQLAlchemy – General-purpose ORM for Python applications.
➢ Example:
class Employee(models.Model):
ename = models.CharField(max_length=100)
deptno = models.IntegerField()
salary = models.DecimalField(max_digits=10, decimal_places=2)
def __str__(self):
return self.ename
➢ A model is a class that represents a table in the database. Each attribute
of the class corresponds to a column in the table.
➢ Once the model is defined, it needs to be migrated to create a database
table.
➢ In Django, run these commands:
o python manage.py makemigrations
o python manage.py migrate
➢ Importance of Database Models:
o Abstraction – Developers work with objects instead of SQL queries.
o Data Validation – Enforces data integrity (e.g., maximum length in
CharField).
o Scalability – Easily modify the model and update the database
structure.
o Cross-Database Support – Works with multiple database backends
without changing code.
5. Explain Database with Tkinter in details.
➢ Tkinter is the standard GUI library in Python, used for building graphical
applications. When combined with a database (such as MySQL or SQLite),
it allows users to store, retrieve, and manipulate data through an
interactive interface.
➢ Common Applications:
o Employee management systems
o Student record management
o Inventory management
➢ To use a database in Tkinter, first establish a connection.
➢ Tkinter widgets like Entry, Button, Label, and Listbox are used to display
and manage database data.
import tkinter as tk
import mysql.connector
# Connect to MySQL
conn = mysql.connector.connect(
host="localhost",
user="root",
password="",
database="test_db"
)
cur = conn.cursor()
def insert_data():
name = entry_name.get()
salary = entry_salary.get()
cur.execute("INSERT INTO emp (name, salary) VALUES (%s, %s)",
(name, salary))
conn.commit()
show_data()
# Tkinter GUI
root = tk.Tk()
root.title("Employee Database")
tk.Label(root, text="Name:").pack()
entry_name = tk.Entry(root)
entry_name.pack()
tk.Label(root, text="Salary:").pack()
entry_salary = tk.Entry(root)
entry_salary.pack()
conn.close()
➢ Advantages:
o Data Persistence – Stores data permanently.
o Easy Data Handling – GUI simplifies interaction.
o User-Friendly Interface – No need to use command-line SQL.
o Real-Time Updates – Fetch and display updated data dynamically.