Home > Mobile >  Django: split one model instance into two
Django: split one model instance into two

Time:03-09

I have a Django model Adventure with two datetime fields:

from django.db import models

class Adventure(models.Model):
    start_time = models.DateTimeField()
    end_time = models.DateTimeField()
    (...)

There's an instance of Adventure, let's say:

Adventure(start_time=TIME_1, end_time=TIME_2, ...)

Assuming there is some TIME_X between TIME_1 and TIME_2 (TIME_1 < TIME_X < TIME_2), how can I split one Adventure object into two separate objects, so after splitting I would have:

#first instance
Adventure(start_time=TIME_1, end_time=TIME_X, ...)

#second instance
Adventure(start_time=TIME_X, end_time=TIME_2, ...)

Adventure has more fields, which should be the same for both instances (except for PK, of course).

CodePudding user response:

You can do it with a method:

import copy

original_adventure = Adventure(start_time=TIME_1, end_time=TIME_2, ...)

adventure_split_1, adventure_split_2 = split_adventure(original_adventure, TIME_MIDDLE)

def split_adventure(adventure, middle_time):
    adventure_split_1 = copy.deepcopy(adventure)
    adventure_split_1.end_time = middle_time

    adventure_split_2 = copy.deepcopy(adventure)
    adventure_split_2.start_time = middle_time
    
    return (adventure_split_1, adventure_split_2)

CodePudding user response:

You could simply use orm methods to change one existing object and create only one new object:

# Get the first instance
adventure = Adventure.objects.get(start_time=TIME_1, end_time=TIME_2, ...)
middle_time = TIME_X

# save old end_time
old_end_time = adventure.end_time

# Modify first instance and save to DB
adventure.end_time = middle_time
adventure.save()

# Create new instance
adventure.pk = None
adventure.start_time = middle_time
adventure.end_time = old_end_time
adventure.save()  # This will create a new object

As a result you will have two database entries with your other attributes the same except for the two start_time and end_time attributes.

  • Related