Skip to content

Commit 2328a6c

Browse files
15 - Writing & Reading data in Python Shell
1 parent 04daebf commit 2328a6c

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
# Writing & Reading Data via models.py in Django
2+
3+
4+
### 1. Install dataclasses
5+
```
6+
pip install dataclasses
7+
```
8+
9+
### 2. Data in a Python Class
10+
11+
```python
12+
from dataclasses import dataclass
13+
14+
@dataclass
15+
class BlogPost:
16+
title: str
17+
content: str
18+
```
19+
20+
```python
21+
obj = BlogPost()
22+
```
23+
24+
```python
25+
obj = BlogPost(title='Hello World', content='This is awesome')
26+
```
27+
28+
29+
### 3. Data in a Django Model Class
30+
31+
```python
32+
# models.py
33+
34+
from django.db import models
35+
36+
37+
class Article(models.Model):
38+
title = models.TextField()
39+
content = models.TextField()
40+
```
41+
42+
43+
#### Writing
44+
```python
45+
obj = Article(title='Hello World', content='This is awesome')
46+
obj.save()
47+
print(obj.id)
48+
```
49+
or
50+
51+
```python
52+
obj2 = Article.objects.create(title='Hello World Again', content='This is awesome')
53+
print(obj2.id)
54+
```
55+
56+
#### Reading
57+
58+
```python
59+
obj = Article.objects.get(id=1)
60+
```

0 commit comments

Comments
 (0)