Model relationship - pai-plznw4me/django-initializer GitHub Wiki

One to Many or (Many to one)

μž₯κ³ μ—μ„œ One to Many λͺ¨λΈμ„ 생성할 λ•Œ λŠ” ForeignKey 을 μ‚¬μš©ν•΄μ„œ μ—°κ²°ν•œλ‹€.
μž¬κ·€μ  관계(μžκΈ°μžμ‹ μ„ μ°Έμ‘°ν•˜λŠ”κ²ƒλ„ κ°€λŠ₯ν•˜λ‹€. κ·Έλ•ŒλŠ” μ•„λž˜μ™€ 같이 model 뢀뢄에 'self'을 λ„£μ–΄μ£Όλ©΄ λœλ‹€.)
(친ꡬ μΆ”κ°€ κΈ°λŠ₯을 μƒκ°ν•΄λ³΄μž)

To create a recursive relationship an object that has a many-to-one relationship with itself use

models.ForeignKey('self', on_delete=models.CASCADE).

예제

μž₯κ³  κ³΅μ‹λ¬Έμ„œμ—μ„œ μ†Œκ°œν•˜λŠ” One to Many
μžλ™μ°¨μ™€ μžλ™μ°¨ 생산 곡μž₯의 관계λ₯Ό ν‘œν˜„ν•œλ‹€.
ν•˜λ‚˜μ˜ 곡μž₯(manufacturer)μ—μ„œ μ—¬λŸ¬ carλ₯Ό μƒμ„±ν•œλ‹€.

from django.db import models

class Car(models.Model):
    manufacturer = models.ForeignKey(
        'Manufacturer',
        on_delete=models.CASCADE,
    )
    # ...

class Manufacturer(models.Model):
    # ...
    pass
pic

μ°Έμ‘° 객체 μ–»μ–΄μ˜€κΈ°

μžμ‹ μ„ μ°Έμ‘°ν•˜λŠ” table 의 instance 을 μ°Ύκ³  μ‹Άμ„λ•ŒλŠ” <instance이름>_set 을 μ‚¬μš©ν•œλ‹€.
μœ„ μ•„λž˜ μ˜ˆμ‹œ μ—μ„œλŠ” νŠΉμ • Manufacture instance 을 μ°Έμ‘°ν•˜λŠ” λͺ¨λ“  Car instances 듀을 κ°€μ Έμ˜¨λ‹€.

# μ˜ˆμ‹œ 1
m = Manufacturer.objects.first()
cars = m.car_set.all()
# μ˜ˆμ‹œ 2
q.choice_set.create(choice_text='Not much', votes=0)
q.choice_set.create(choice_text='The sky', votes=0)
c = q.choice_set.create(choice_text='Just hacking again', votes=0)

reference official guide recursive relationship

Many to Many

recursive relationship

Many to Many field 을 Admin Site 에 λ“±λ‘μ‹œ μ•„λž˜μ™€ 같은 μž‘μ—… μˆ˜ν–‰

class ChecklistAdmin(admin.ModelAdmin):
    model = Checklist
    list_display = ["start_date", "end_date", "end_time", "desc", "complete"]
    filter_horizontal = ("assignee",)

Read

@csrf_exempt
def show_checklist(request):
    """
    Description:
        checklist instnace 을 생성 ν•œ ν›„ 'show_checklist.html' νŽ˜μ΄μ§€ ν•˜λ‹¨
        ν…Œμ΄λΈ” body 뢀뢄에 λΆ™μ—¬ λ„£μŠ΅λ‹ˆλ‹€.
    """
    checklist = Checklist.objects.all()
    assignee = Checklist.objects.first().assignee.all()
    context = {'checklist_assignee': zip(checklist, assignee)}
    content = render(request, template_name='school_management_app/show_checklist.html', context=context).content
    content = content.decode('utf-8')
    data = {'content': content}
    return JsonResponse(data)

write

    trgt_publisher = CustomUser.objects.get(username=random_publisher[i][0])
        todo = Todo.objects.create(start_date=rand_start_date[i],
                                   end_date=rand_end_date[i],
                                   publisher=trgt_publisher,
                                   desc=random_desc[i][0],
                                   complete=random_complete[i][0])
        for assignee_name in random_assignee[i]:
            tmp_user = CustomUser.objects.get(username=assignee_name)
            todo.assignee.add(tmp_user)
    

One to One

⚠️ **GitHub.com Fallback** ⚠️