Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django loaddata ignore existing objects

I have a fixture with list of entries. eg:

[
  {
    "fields": {
      "currency": 1,
      "price": "99.99",
      "product_variant": 1
    },
    "model": "products.productprice",
    "pk": 1
  },
  {
    "fields": {
      "currency": 2,
      "price": "139.99",
      "product_variant": 1
    },
    "model": "products.productprice",
    "pk": 2
  }
]

This is only initial data for each entry (The price might change). I would like to be able to add another entry to that fixture and load it with loaddata but without updating entries that already exist in the database.

Is there any way to do that? Something like --ignorenonexistent but for existing entries.

like image 868
Quba Avatar asked Dec 10 '18 10:12

Quba


Video Answer


1 Answers

If you keep pk in the json like that, you will always overwrite the first two records in product.productprice.

I would use "pk: null". This way, you will always create new record with every load.

So if you want to create a new price:

[
  {
    "fields": {
      "currency": 1,
      "price": "99.99",
      "product_variant": 1
    },
    "model": "products.productprice",
    "pk": 1
  },
  {
    "fields": {
      "currency": 2,
      "price": "139.99",
      "product_variant": 1
    },
    "model": "products.productprice",
    "pk": 2
  },
  {
    "fields": {
      "currency": 4,
      "price": "9.99",
      "product_variant": 1
    },
    "model": "products.productprice",
    "pk": null
  }
]

The first two records are always be the same, but if you already added a third one ( pk:3 ) with the last section you will create a new productprice with pk: 4.

BTW: if your currency field is an other primary key(with autoincrement), you can put "null" there too, a new primary key will be generated.

like image 88
Mark2 Avatar answered Sep 28 '22 05:09

Mark2