Home > database >  Ceating two objects instead of one in Django
Ceating two objects instead of one in Django

Time:10-02

I want to create an object with transmitting some data from other model. And it works good, but instead of creation one object of model, I got two objects.

I create one object and try modify it, but it saves two objects, created and modified. I want to save only one object, which was modified. I am using the approach that was suggested to me: Django instance in model form

Views

topic = Topic.objects.get(id=pk)
room = Room.objects.create(topic=topic)
form = RoomForm(request.POST, instance=room)
if request.method == 'POST':
    if form.is_valid():
        room = form.save(commit=False)
        room.host=request.user
        room.save()
        return redirect('home')

CodePudding user response:

Don't create an object yourself; let the form do this. With your approach, you create one in the GET request, and one in the POST request:

def my_view(request, pk):
    topic = Topic.objects.get(id=pk)
    # no create
    if request.method == 'POST':
        form = RoomForm(request.POST)
        if form.is_valid():
            form.instance.topic_id = pk
            form.instance.host = request.user
            form.save()
            return redirect('home')
    else:
        form = RoomForm()
    # …

CodePudding user response:

if you want to modify an object which created before just do this. search from your model and update the field you want

Topic.objects.filter(id=pk).update(fields = something)

that it bro. remember use if when you want to sure that the object you choose is the right one

  • Related