logo
down
shadow

Saving django model instance into another model


Saving django model instance into another model

By : user2955956
Date : November 22 2020, 10:48 AM
fixed the issue. Will look into that further I have 2 models that inherit from an abstract model. I am using one for relevant data and the other one for archived data. They have the same fields and methods. I would like to create a post_save signal on model A so an instance will be created in model B whenever a new record is created, so far the options out there are not very elegant: , I think that iterating over field list is more predictable way:
code :
a = A.objects.get(id=1)
data = dict([field.name, getattr(a, field.name) for field in a._meta.fields])
b = B(**data)
b.pk = None
b.save()


Share : facebook icon twitter icon
Django: Get Model instance from Form without saving

Django: Get Model instance from Form without saving


By : Sarit A.
Date : March 29 2020, 07:55 AM
To fix this issue Let say I have a django ModelForm which I want to edit before saving.
code :
model_instance = form.save(commit=False)
model_instance.some_field = value
model_instance.save()
Django model instance not saving but no errors thrown

Django model instance not saving but no errors thrown


By : Umesh Kamboj
Date : March 29 2020, 07:55 AM
wish helps you get_or_create returns tuple
code :
 user, created = User.objects.get_or_create(email=request.GET['user_email'][0])
Creating and saving non-empty Django model instance as part of subclass instance

Creating and saving non-empty Django model instance as part of subclass instance


By : Tayyaba Khan
Date : March 29 2020, 07:55 AM
wish help you to fix your issue Ok, I found an explanation....
It has something to do with inheritance, namely further in the code I wanted to create instance of Person's subclass. So there was another class:
code :
class Person(models.Model):
    user = models.ForeignKey(User)
    phone_number = models.CharField(max_length=20, blank=True)
    address     = models.CharField(max_length=200, blank=True)

class ConnectedPerson(Person):
    connection = models.ForeignKey(AnotherClass)
    # etc..
#creating instance of Person:
person = Person(user=request.user, phone_number='111111')
person.save(force_insert=True)

c_person = ConnectedPerson(id=person.id, connection=instance_of_another_c)
#creating person but not saving it
person = Person(user=request.user, phone_number='111111')

######
#later
###### 

#creating subclass instance and saving
c_person = ConnectedPerson(user=request.user, connection=instance_of_another_c)
c_person.save()

#saving super class instance as part of subclass instance
person.pk = super(ConnectedPerson, c_person).pk
person.save()
Django saving model instance fails

Django saving model instance fails


By : user3400869
Date : March 29 2020, 07:55 AM
seems to work fine For some reason I don't get this rather simple operation work. I'm trying to save model instance to database (sqllite), but the saving fails with no error message (just showing 500, internal server error). I have made my database with migrations (make migrations, migrate) and it should be up to date. So here is my view code: , Use:
code :
datetime.datetime.now()
In django how do I add another instance to an inline model before saving it?

In django how do I add another instance to an inline model before saving it?


By : preethysundar
Date : March 29 2020, 07:55 AM
Hope this helps Use below method in parent model admin and do the necessary calculation to achieve the same:
code :
def save_model(self, request, obj, form, change):
        for d in obj.voucherdetail_set.all():
            if d.value:
                amt_exists = True                    
                pass
            else:
                amt_exists =False

    if amt_exists is False:
        try:
            dr_detail = VoucherDetail()
            dr_detail.voucher = Voucher.objects.get(pk=obj.pk)
            dr_detail.narration = "Client remarks"

            dr_detail......
            dr_detail.save()
        except Exception,e:
            print e
    obj.save()
Related Posts Related Posts :
  • pretty printing numpy ndarrays using unicode characters
  • Frequent pattern mining in Python
  • How can I make a set of functions that can be used synchronously as well as asynchronously?
  • Convert one dice roll to two dice roll
  • count occourrence in a list
  • Writing an If condition to filter out the first word
  • to read file and compare column in python
  • Install python-numpy in the Virtualenv environment
  • `.select_by_visible_text()` is failed to select element?
  • Unable to send data multiple requests in a single connection — socket error
  • Pandas HDFStore unload dataframe from memory
  • Creating a custom admin view
  • How do you get the user role of the currently logged in user in Ckan?
  • Speed up Numpy Meshgrid Command
  • Python error - name lengths
  • appending text to a global variable
  • Python Mistake - Number of letters in name
  • Searching for a sequence in a text
  • Testing logging output with pytest
  • How do I change my default working directory for Python (Anaconda) on VSCode?
  • .lower() for x in list, not working, but works in another scenario
  • Program gives error "List indices must not be string"
  • pyqt: Memory Usage
  • Confused about classes in Learn Python the Hard Way ex43?
  • Extracting unrecognized information from many CSV files
  • How do I connect to Postgresql server from Python?
  • Append rows to a pandas DataFrame without making a new copy
  • Scrapy: Importing a package from the project that's not in the same directory
  • launching Excel application using Python to view the CSV file , but CSV file is opening in read mode and cant view the d
  • Making a list in user-defined functions
  • Pyserial microcontroller to host communication
  • Plotting a line in between subplots
  • function not returning value. Error "NameError: name 'urlss' is not defined"
  • How to perform cartesian product with Tensorflow?
  • Multiple independent random number streams from single seed
  • I Need a simple and short python3 code that count secounds in a background process
  • No module named constants
  • from django 1.4 to django 1.5- argument 'verify_exists' what s replacement?
  • Slash replacement inside a raw string
  • Reordering columns/rows of a pivot_table?
  • MySQLdb.cursors.Cursor.execute does not work
  • Python module being reimported when imported at different places
  • Is the Session object from Python's Requests library thread safe?
  • Python Regex: Finding First and Last Names
  • Order by selection in List view of OpenERP 7.0
  • Reading input values in ipython notebook
  • List of dictionaries - how to read a specific value in a dictionary
  • writing os.system output to file
  • Create dictionary from points list and multiple attribute lists
  • How to write a table line by line with for loop
  • Map projection and forced interpolation
  • Django FBV's "render_to_response" equivalent in Class-Based-View?
  • Paramiko raises "SFTPError: Garbage packet received"
  • python pandas operations on columns
  • python list appending is not working
  • Speeding up matplotlib scatter plots
  • For each element of the list find closest date from a different list
  • How to prepend new rows at the beginning of an existing csv file?
  • how to make database robust to process kills with sqlite postgress and sqlalchemy?
  • finding a set of ranges that a number fall in
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org