Django 컨텐츠 유형은 정확히 어떻게 작동합니까?
Django의 콘텐츠 유형 개념을 파악하는 데 어려움을 겪고 있습니다. 그것은 매우 해킹 감을 느끼고 궁극적으로 파이썬이 일을하는 방식에 반합니다. Django를 사용하려면 프레임 워크의 범위 내에서 작업해야합니다.
그래서 나는 누군가가 컨텐츠 유형의 작동 방식과 구현 방법에 대한 실제적인 예를 제시 할 수 있는지 궁금합니다. 필자가 검토 한 거의 모든 자습서 (주로 블로그)는 실제로 개념을 다루는 데 큰 도움이되지 않습니다. 그들은 Django 문서가 사라진 곳에서 픽업하는 것처럼 보입니다 (어딘가처럼 보입니다).
작업에 컨텐츠 유형 프레임 워크를 사용 하시겠습니까?
"이 모델들 중 어떤 모델이 다른 모델과 같은 방식으로 관련 될 필요가 있습니까? 그리고 / 또는 이러한 관계를 나중에 예상치 못한 방식으로 재사용 할 것입니까?" 우리가이 질문을하는 이유는 이것이 콘텐츠 유형 프레임 워크가 가장 잘하는 것이기 때문입니다. 모델간에 일반적인 관계를 만듭니다. Blah blah, 몇 가지 코드를 살펴보고 무슨 뜻인지 봅시다.
# ourapp.models
from django.conf import settings
from django.db import models
# Assign the User model in case it has been "swapped"
User = settings.AUTH_USER_MODEL
# Create your models here
class Post(models.Model):
author = models.ForeignKey(User)
title = models.CharField(max_length=75)
slug = models.SlugField(unique=True)
body = models.TextField(blank=True)
class Picture(models.Model):
author = models.ForeignKey(User)
image = models.ImageField()
caption = models.TextField(blank=True)
class Comment(models.Model):
author = models.ForeignKey(User)
body = models.TextField(blank=True)
post = models.ForeignKey(Post)
picture = models.ForeignKey(Picture)
자, 우리는 이론적으로이 관계를 만들 수있는 방법이 있습니다. 그러나 파이썬 프로그래머로서, 당신의 뛰어난 지능은 이것이 짜증나고 더 잘 할 수 있다고 말하고 있습니다. 하이 파이브!
컨텐츠 유형 프레임 워크를 입력하십시오!
자, 이제 우리는 모델을 자세히 살펴보고보다 "재사용 가능하고"직관적 인 모델로 재 작업 할 것입니다. Comment
모델 에서 두 개의 외래 키를 제거 하고로 대체 해 봅시다 GenericForeignKey
.
# ourapp.models
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
...
class Comment(models.Model):
author = models.ForeignKey(User)
body = models.TextField(blank=True)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey()
그래서 무슨 일이야? 글쎄, 우리는 다른 모델과의 일반적인 관계를 위해 필요한 코드를 추가하고 추가했습니다. 공지 단지보다이 방법 GenericForeignKey
뿐만 아니라 ForeignKey
에 ContentType
와 PositiveIntegerField
에 대한이 object_id
. 이 필드들은 장고에게 어떤 종류의 객체와 관련이 있고 그 객체의 id가 무엇인지 알려주기위한 것입니다. 실제로 Django는 이러한 관련 객체를 조회해야하기 때문에 이것이 의미가 있습니다.
글쎄, 그것은 파이썬과 같지 않습니다 ... 그것의 추악한!
You are probably looking for air-tight, spotless, intuitive code that would make Guido van Rossum proud. I get you. Let's look at the GenericRelation
field so we can put a pretty bow on this.
# ourapp.models
from django.contrib.contenttypes.fields import GenericRelation
...
class Post(models.Model):
author = models.ForeignKey(User)
title = models.CharField(max_length=75)
slug = models.SlugField(unique=True)
body = models.TextField(blank=True)
comments = GenericRelation('Comment')
class Picture(models.Model):
author = models.ForeignKey(User)
image = models.ImageField()
caption = models.TextField(blank=True)
comments = GenericRelation('Comment')
Bam! Just like that you can work with the Comments for these two models. In fact, let's go ahead and do that in our shell (type python manage.py shell
from your Django project directory).
>>> from django.contrib.auth import get_user_model
>>> from ourapp.models import Picture
# We use get_user_model() since we are referencing directly
User = get_user_model()
# Grab our own User object
>>> me = User.objects.get(username='myusername')
# Grab the first of our own pictures so we can comment on it
>>> pic = Picture.objects.get(author=me)
# Let's start making a comment for our own picture
>>> pic.comments.create(author=me, body="Man, I'm cool!")
# Let's go ahead and retrieve the comments for this picture now
>>> pic.comments.all()
[<Comment: "Man, I'm cool!">]
It's that simple.
What are the other practical implications of these "generic" relations?
Generic foreign keys allow for less intrusive relations between various applications. For example, let's say we pulled the Comment model out into it's own app named chatterly
. Now we want to create another application named noise_nimbus
where people store their music to share with others.
What if we want to add comments to those songs? Well, we can just draw a generic relation:
# noise_nimbus.models
from django.conf import settings
from django.contrib.contenttypes.fields import GenericRelation
from django.db import models
from chatterly.models import Comment
# For a third time, we take the time to ensure custom Auth isn't overlooked
User = settings.AUTH_USER_MODEL
# Create your models here
class Song(models.Model):
'''
A song which can be commented on.
'''
file = models.FileField()
author = models.ForeignKey(User)
title = models.CharField(max_length=75)
slug = models.SlugField(unique=True)
description = models.TextField(blank=True)
comments = GenericRelation(Comment)
I hope you guys found this helpful as I would have loved to have come across something that showed me the more realistic application of GenericForeignKey
and GenericRelation
fields.
Is this too good to be true?
As with anything in life, there are pros and cons. Anytime you add more code and more abstraction, the underlying processes becomes heavier and a bit slower. Adding generic relations can add a little bit of a performance dampener despite the fact it will try and smart cache its results. All in all, it comes down to whether the cleanliness and simplicity outweighs the small performance costs. For me, the answer is a million times yes.
There is more to the Content Types framework than I have displayed here. There is a whole level of granularity and more verbose usage, but for the average individual, this is how you will be using it 9 out of 10 times in my opinion.
Generic relationizers(?) beware!
A rather large caveat is that when you use a GenericRelation
, if the model which has the GenericRelation
applied (Picture
) is deleted, all related (Comment
) objects will also be deleted. Or at least as of the time of this writing.
Ok well the direct answer to your question: ( from the django source code ) is: Media Types parsing according to RFC 2616, section 3.7.
Which is the tears way of saying that it reads/allows-you-to-modify/passes along the 'Content-type' httpd header.
However, you are asking for a more practice usage example. I have 2 suggestions for you:
1: examine this code
def index(request):
media_type='text/html'
if request.META.has_key('CONTENT_TYPE'):
media_type = request.META['CONTENT_TYPE'].split(';')[0]
if media_type.lower() == 'application/json':
return HttpResponse("""{ "ResponseCode": "Success"}""", content_type="application/json; charset=UTF-8")
return HttpResponse("<h1>regular old joe</h1>");
2: remember django is python, and as such it wields the power of the python community. There are 2 awesome RESTFul plugins to django. So if you want to see how deep the rabbit whole goes you can check out.
I suggest going through the django-rest-framework tutorial which will address 'acting on different content/types' specifically. Note: It is common practice to use the content-type header to 'version' restful API's.
참고URL : https://stackoverflow.com/questions/20895429/how-exactly-do-django-content-types-work
'development' 카테고리의 다른 글
IPA 재 서명 (iPhone) (0) | 2020.07.05 |
---|---|
Amazon S3 CORS (Cross-Origin Resource Sharing) 및 Firefox 도메인 간 글꼴로드 (0) | 2020.07.05 |
Android에서 logcat 버퍼를 비우는 방법 (복제) (0) | 2020.07.05 |
리소스 서버에 대한 OAuth 2.0 액세스 토큰의 유효성을 검사하는 방법은 무엇입니까? (0) | 2020.07.05 |
Twiny를 사용할 때 Python Matplotlib 그림 제목이 축 레이블과 겹칩니다. (0) | 2020.07.05 |