I have a problem with the Json values that are released by the Django. After I serialize my object from the views.py the user outputs a the id of the primary key not the value of the primary key. I tried the Natural keys technique in models.py. How can I get the value output instead of id?
views.py
def load_post(request):
serials = serialize('json', Post.objects.all().order_by(
"-id"))
return JsonResponse(serials, safe=False)
models.py
from django.contrib.auth.models import AbstractUser
from django.db import models
#Natural Key technique
class UserManager(models.Manager):
def get_by_natural_key(self, username):
return self.get(username=username)
class User(AbstractUser):
objects = UserManager()
class Post(models.Model):
id = models.AutoField(primary_key=True)
user = models.ForeignKey(
'User', on_delete=models.CASCADE, related_name='user')
post = models.TextField(max_length=280, blank=True)
timestamp = models.DateTimeField(auto_now_add=True)
likes = models.IntegerField(default=0)
def __str__(self):
return f"id: {self.id}, username: {self.user}, post: {self.post}, datetime: {self.timestamp}, likes: {self.likes}"
Json output
[
{
"model":"network.post",
"pk":3,
"fields":{
"user":1, #This should be a username
"post":"afefawfawefawf",
"timestamp":"2020-08-07T14:38:54.444Z",
"likes":0
}
},
{
"model":"network.post",
"pk":2,
"fields":{
"user":1, #This should be a username
"post":"afefawfawefawf",
"timestamp":"2020-08-07T14:38:18.687Z",
"likes":0
}
},
{
"model":"network.post",
"pk":1,
"fields":{
"user":2, #This should be a username
"post":"sfoawefoawemfowf",
"timestamp":"2020-08-07T14:28:09.784Z",
"likes":0
}
}
]
If you want the natural key to be output by the built-in Django serializer, you need two additional things:
natural_key()
method on the User
modeluse_natural_foreign_keys=True
to the call to serialize()
The process is described in the Django documentation here: https://docs.djangoproject.com/en/3.1/topics/serialization/#serialization-of-natural-keys
models.py
...
class User(AbstractUser):
objects = UserManager()
def natural_key(self):
return self.username
...
views.py
def load_post(request):
serials = serialize('json', Post.objects.all().order_by("-id"), use_natural_foreign_keys=True)
return JsonResponse(serials, safe=False)
The get_by_natural_key()
method is not used in serialization, but is needed to deserialize data with natural keys in it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.