[Django]SNSアプリ1

### アプリケーションの作成
$ python manage.py startapp sns

– settingsにアプリケーション名を追加
/django_app/settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'hello',
    'sns',
]

### アプリケーションの設計
– 機能の洗い出し
– データベース設計
– 各ページの設計

### モデルの作成
– テーブルはUser, Message, Group, Friend, Good
– Message: owner(投稿者), group, content, share_id, good_count, share_count, pub_date
– Group: owner, title
– Friend: owner, user, group
– Good: owner, message
/sns/models.py

from django.db import models
from django.contrib.auth.models import User

# Message
class Message(models.Model):
	owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='message_owner')
	group = models.ForeignKey('Group', on_delete=models.CASCADE)
	content = models.TextField(max_length=1000)
	share_id = models.IntegerField(default=-1)
	good_count = models.IntegerField(default=0)
	pub_date = models.DateTimeField(auto_now_add=True)

	def __str__(self):
		return str(self.content) + ' (' + str(self.owner) + ')'

	class Meta:
		ordering = ('-pub_date',)

# Group
class Group(models.Model):
	owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='group_owner')
	title = models.CharField(max_length=100)

	def __str__(self):
		return '<' + self.title + '(' + str(self.owner) + ')>'

# Friend
class Friend(models.Model):
	owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='friend_owner')
	user = models.ForeignKey(User, on_delete=models.CASCADE)
	group = models.ForeignKey(Group, on_delete=models.CASCADE)

	def __str__(self):
		return str(self.user) + ' (group:"' + str(self.group) + '")'

# Good
class Good(models.Model):
	owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='good_owner')
	message = models.ForeignKey(Message, on_delete=models.CASCADE)

	def __str__(self):
		return 'good for "' + str(self.message) + '" (by' + str(self.owner) + ')'

– -pub_dateはpub_dateの大きい順

### マイグレーション
$ python manage.py makemigrations sns
$ python manage.py migrate

### admin.py
/sns/admin.py

from django.contrib import admin
from .models import Message, Friend, Group, Good

admin.site.register(Message)
admin.site.register(Friend)
admin.site.register(Group)
admin.site.register(Good)

$ python manage.py runserver 192.168.33.10:8000

– AddUserからpublicユーザの作成
– ユーザ作成
– publicグループを用意