models.py
class Post(models.Model):
poster = models.ForeignKey(User, on_delete=models.CASCADE)
content = models.TextField(max_length=500)
timestamp = models.DateTimeField(default=timezone.now)
likes = models.ManyToManyField(User, blank=True, related_name='likes')
views.py
def index(request):
if request.method == 'POST':
data = json.loads(request.body)
# postid = data.get('postid', '')
postcontent = data.get('postcontent', '')
print(postcontent)
obj, created = Post.objects.update_or_create(
poster=request.user, content=postcontent,
defaults={'content': postcontent})
by using update_or_create views.py
is able to create new entries (
). But, on the time of edit
, it creates new
entry (
). I know that , method update_or_create need some unique entity (an id
for instance) which _view _or JS’s fetch can’t generate
while creating new object
… what unique
value can go inside _update_orcreate method ?
I’m sorry, I’m not following what you’re trying to ask here.
When you call update_or_create, Django will search for an existing instance that satisfies the search criteria given. If no such instance is found, it will create a new instance with the values given in the defaults
dict.
So using your snippet as an example, Django is going to look for an existing object where poster=request.user
and content=postcontent
. If it doesn’t already find one matching those criteria, it will create a new Post object, with content = postcontent
. (Notice, however, you’re not setting the poster
when you do this.)