Study Anything ๐Ÿง

[Django] ํ•œ ํ”„๋กœ์ ํŠธ ๋‚ด์—์„œ ๋‹ค๋ฅธ ์•ฑ์˜ ๋ชจ๋ธ ์‚ฌ์šฉํ•˜๊ธฐ ๋ณธ๋ฌธ

์Šคํ„ฐ๋””/Web

[Django] ํ•œ ํ”„๋กœ์ ํŠธ ๋‚ด์—์„œ ๋‹ค๋ฅธ ์•ฑ์˜ ๋ชจ๋ธ ์‚ฌ์šฉํ•˜๊ธฐ

์†” 2022. 2. 9. 00:03

ํ”„๋กœ์ ํŠธ๋ฅผ ์—ฌ๋Ÿฌ ๋ช…์ด ํ•จ๊ป˜ ์ง„ํ–‰ํ•˜๋‹ค๋ณด๋‹ˆ ๊ฐ ํŒ€์›์ด ์„œ๋กœ ๋‹ค๋ฅธ ์•ฑ์„ ๊ตฌํ˜„ํ•˜๊ฒŒ ๋˜๋Š”๋ฐ,

์ด ๋•Œ ๋‹ค๋ฅธ ์•ฑ์˜ ๋ชจ๋ธ ํ•„๋“œ๋ฅผ ์™ธ๋ž˜ํ‚ค๋กœ ์‚ฌ์šฉํ•˜๊ฑฐ๋‚˜ ๋ชจ๋ธ ์ž์ฒด๋ฅผ ๋‚ด ์•ฑ์—์„œ ์‚ฌ์šฉํ•˜๋Š” ๊ฒฝ์šฐ

์–ด๋–ป๊ฒŒ ์‚ฌ์šฉํ•˜๋ฉด ๋˜๋Š”์ง€์— ๋Œ€ํ•œ ๋‚ด์šฉ์„ ๋‹ค๋ค„๋ณด๋ ค๊ณ  ํ•œ๋‹ค.

ํŽธ์˜์ƒ ๋‚ด ์•ฑ์˜ ์ด๋ฆ„์€ 'myapp', ๋‹ค๋ฅธ ํŒ€์›์˜ ์•ฑ ์ด๋ฆ„์€ 'yourapp'์œผ๋กœ ์„œ์ˆ ํ•˜๋„๋ก ํ•˜๊ฒ ๋‹ค.

 

 

๋ชจ๋ธ๋“ค์˜ ๋‚ด์šฉ์€ ๋‹ค์Œ๊ณผ ๊ฐ™๋‹ค.

# myapp/models.py

class Review(models.Model):
    ...
    userId = models.ForeignKey(User, on_delete=models.CASCADE)
    ...
    
# yourapp/models.py

class User(models.Model):
    ...

Review ๋ชจ๋ธ์—์„œ๋Š” User ๋ชจ๋ธ์„ ์™ธ๋ž˜ํ‚ค๋กœ ์‚ฌ์šฉํ•˜์ง€๋งŒ ๋‚ด๊ฐ€ ๋งŒ๋“  ์•ฑ์—๋Š” ํ•ด๋‹น ๋ชจ๋ธ์ด ์กด์žฌํ•˜์ง€ ์•Š๊ณ 

ํŒ€์›์ด ๋งŒ๋“  ๋ชจ๋ธ์˜ ๋‚ด์šฉ์€ yourapp/models.py ํŒŒ์ผ์— ์กด์žฌํ•˜๋Š” ์ƒํ™ฉ์ด๋‹ค.

 

 

# myapp/views.py

def post(self, request):
    data = request.data
    r : Review = Review (
        userId = User.objects.get(id=uid),
        ...
    )
    r.save()

์ด ๊ฒฝ์šฐ๋Š” ๋ฐ›์€ ๋ฐ์ดํ„ฐ๋ฅผ ์ด์šฉํ•ด์„œ ๋‚ด ๋ชจ๋ธ์— ๋„ฃ์œผ๋ ค๊ณ  ํ•˜๋Š”๋ฐ ์™ธ๋ž˜ํ‚ค๋กœ ์—ฐ๊ฒฐ๋˜์–ด ์žˆ์–ด์„œ

User ๋ชจ๋ธ์„ ์‚ฌ์šฉํ•ด์•ผ ํ•˜๋Š” ๊ฒฝ์šฐ์ด๋‹ค.

 

 

์•ฑ ๋ณ„๋กœ ๊ธฐ๋Šฅ์„ ๊ด€๋ฆฌํ•˜๋Š” ๊ฒƒ์ด ์žฅ๊ณ ์˜ ์žฅ์ ์ด์ง€๋งŒ ๊ฐ ์•ฑ์— ๋ชจ๋ธ์ด ์ž‘์„ฑ๋˜๋ฉด ๋ชจ๋ธ ๋˜ํ•œ ์•ฑ ๋ณ„๋กœ ๋‚˜๋ˆ ์ง„๋‹ค.

๋”ฐ๋ผ์„œ ๋‹ค๋ฅธ ์•ฑ์˜ ๋ชจ๋ธ์„ ์‚ฌ์šฉํ•˜๊ธฐ ์œ„ํ•ด์„œ๋Š” ๋‹ค์Œ์˜ ๋ฐฉ๋ฒ•์„ ์‚ฌ์šฉํ•˜๋ฉด ๋œ๋‹ค.

# myapp/models.py

from django.db import models
from user.models import User	### ์ด ๋ถ€๋ถ„ ์ถ”๊ฐ€ ###

class Review(models.Model):
	...
# myapp/views.py

from user.models import User	### ์ด ๋ถ€๋ถ„ ์ถ”๊ฐ€ ###

class ReviewView(APIView):
	...
    def post(self, request):
        data = request.data
        r : Review = Review (
            userId = User.objects.get(id=1),
            ...
        )
        r.save()

 

์žฅ๊ณ ๊ฐ€ ํŒŒ์ด์ฌ ์–ธ์–ด๋ฅผ ๊ธฐ๋ฐ˜์œผ๋กœ ํ•˜๊ธฐ ๋•Œ๋ฌธ์—

์œ„ ๋ฐฉ๋ฒ•์ฒ˜๋Ÿผ ๋‹ค๋ฅธ ์•ฑ์— ์ž‘์„ฑ๋œ ๋ชจ๋ธ์„ import ํ•ด์„œ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ์ฒ˜๋Ÿผ ์‚ฌ์šฉํ•˜๋ฉด ๊ฐ„๋‹จํ•˜๊ฒŒ ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ๋‹ค.

 

 

 

 

728x90
Comments