Django Models added to admin

 

Description

 Few core live tables should  be maintained by admin. Django provides the most easiest way to attain it.


start the app


(dj-env) [dj_adm@localhost mysite]$ python manage.py startapp polls

└── polls
    ├── admin.py
    ├── apps.py
    ├── __init__.py
    ├── migrations
    │   └── __init__.py
    ├── models.py
    ├── tests.py
    └── views.py

Models.py

 


 

from django.db import models
from django.utils import timezone
import datetime
# Create your models here.


class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date_published')

def __str__(self):
return self.question_text

def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)


class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)

def __str__(self):
return self.choice_text


deploy models into mysql

makemigrations


(dj-env) [dj_adm@localhost mysite]$ python manage.py makemigrations polls
Migrations for 'polls':
  polls/migrations/0001_initial.py
    - Create model Question
    - Create model Choice

to see the migration changes


(dj-env) [dj_adm@localhost mysite]$ python manage.py sqlmigrate polls 0001
--
-- Create model Question
--
CREATE TABLE `polls_question` (`id` bigint AUTO_INCREMENT NOT NULL PRIMARY KEY, `question_text` varchar(200) NOT NULL, `pub_date` datetime(6) NOT NULL);
--
-- Create model Choice
--
CREATE TABLE `polls_choice` (`id` bigint AUTO_INCREMENT NOT NULL PRIMARY KEY, `choice_text` varchar(200) NOT NULL, `votes` integer NOT NULL, `question_id` bigint NOT NULL);
ALTER TABLE `polls_choice` ADD CONSTRAINT `polls_choice_question_id_c5b4b260_fk_polls_question_id` FOREIGN KEY (`question_id`) REFERENCES `polls_question` (`id`);

deploy into mysql


(dj-env) [dj_adm@localhost mysite]$ python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, polls, sessions
Running migrations:
  Applying polls.0001_initial... OK
 

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| prod_app           |
+--------------------+
2 rows in set (0.00 sec)

mysql> use prod_app
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> show tables
    -> ;
+----------------------------+
| Tables_in_prod_app         |
+----------------------------+
| auth_group                 |
| auth_group_permissions     |
| auth_permission            |
| auth_user                  |
| auth_user_groups           |
| auth_user_user_permissions |
| django_admin_log           |
| django_content_type        |
| django_migrations          |
| django_session             |
| polls_choice               |
| polls_question             |
+----------------------------+
12 rows in set (0.00 sec)

mysql> select * from django_migrations;
+----+--------------+------------------------------------------+----------------------------+
| id | app          | name                                     | applied                    |
+----+--------------+------------------------------------------+----------------------------+
|  1 | contenttypes | 0001_initial                             | 2022-04-08 03:11:43.455234 |
|  2 | auth         | 0001_initial                             | 2022-04-08 03:11:45.039371 |
|  3 | admin        | 0001_initial                             | 2022-04-08 03:11:45.382630 |
|  4 | admin        | 0002_logentry_remove_auto_add            | 2022-04-08 03:11:45.399791 |
|  5 | admin        | 0003_logentry_add_action_flag_choices    | 2022-04-08 03:11:45.414532 |
|  6 | contenttypes | 0002_remove_content_type_name            | 2022-04-08 03:11:45.661499 |
|  7 | auth         | 0002_alter_permission_name_max_length    | 2022-04-08 03:11:45.808548 |
|  8 | auth         | 0003_alter_user_email_max_length         | 2022-04-08 03:11:45.963540 |
|  9 | auth         | 0004_alter_user_username_opts            | 2022-04-08 03:11:45.978634 |
| 10 | auth         | 0005_alter_user_last_login_null          | 2022-04-08 03:11:46.106685 |
| 11 | auth         | 0006_require_contenttypes_0002           | 2022-04-08 03:11:46.116285 |
| 12 | auth         | 0007_alter_validators_add_error_messages | 2022-04-08 03:11:46.135984 |
| 13 | auth         | 0008_alter_user_username_max_length      | 2022-04-08 03:11:46.278144 |
| 14 | auth         | 0009_alter_user_last_name_max_length     | 2022-04-08 03:11:46.448201 |
| 15 | auth         | 0010_alter_group_name_max_length         | 2022-04-08 03:11:46.603843 |
| 16 | auth         | 0011_update_proxy_permissions            | 2022-04-08 03:11:46.624718 |
| 17 | auth         | 0012_alter_user_first_name_max_length    | 2022-04-08 03:11:46.776011 |
| 18 | sessions     | 0001_initial                             | 2022-04-08 03:11:46.881352 |
| 19 | polls        | 0001_initial                             | 2022-04-09 08:53:48.512924 |
+----+--------------+------------------------------------------+----------------------------+
19 rows in set (0.00 sec)


django shell

Question Creation


(dj-env) [dj_adm@localhost mysite]$ python manage.py shell
Python 3.9.10 (main, Feb  9 2022, 00:00:00)
[GCC 11.2.1 20220127 (Red Hat 11.2.1-9)] on linux
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from polls.models import Choice, Question

>>> Question.objects.all()
<QuerySet []>

>>> from django.utils import timezone
>>> q = Question(question_text="What's new?", pub_date=timezone.now())
>>> q.save()


(dj-env) [dj_adm@localhost mysite]$ python manage.py shell
Python 3.9.10 (main, Feb  9 2022, 00:00:00)
[GCC 11.2.1 20220127 (Red Hat 11.2.1-9)] on linux
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from polls.models import Choice, Question
>>> Question.objects.all()
<QuerySet [<Question: What's up?>]>
>>> Question.objects.fi
Question.objects.filter(  Question.objects.first(   
>>> Question.objects.fi
Question.objects.filter(  Question.objects.first(   
>>> Question.objects.filter(id=1)
<QuerySet [<Question: What's up?>]>
>>> Question.objects.filter(question_text__startswith='What')
<QuerySet [<Question: What's up?>]>
>>> Question.objects.get(pub_date__year='2022')
<Question: What's up?>
>>> Question.objects.filter(pub_date__year='2022')
<QuerySet [<Question: What's up?>]>
>>> q=Question.objects.get(pub_date__year='2022')
>>> q1=Question.objects.filter(pub_date__year='2022')
>>> q
<Question: What's up?>
>>> q1
<QuerySet [<Question: What's up?>]>
>>> q1
q1

>>> q.was_published_recently()
True

choice creation


>>> q.choice_set.all()
<QuerySet []>
>>> q.choice_set.create(choice_text='Not much', votes=0)
<Choice: Not much>
>>> q.choice_set.create(choice_text='The sky', votes=0)
<Choice: The sky>
>>> c = q.choice_set.create(choice_text='Just hacking again', votes=0)

>>> c.question
<Question: What's up?>
>>> c.question_id
1
>>> c.choice_text
'Just hacking again'

>>> c = q.choice_set.filter(choice_text__startswith='Just hacking')
>>> c.delete()
(1, {'polls.Choice': 1})
>>> Choice.objects.all()
<QuerySet [<Choice: Not much>, <Choice: The sky>]>

Adding models to admin

from django.contrib import admin

# Register your models here.

from .models import Question
admin.site.register(Question)





Comments

Popular posts from this blog

Django Server setup with Apache with mod_wsgi in Centos 9

Mysql Installation on CentOS 9

Install mysql8 on centOS 9 and integrating with Django