Home > Blockchain >  How to create a django model record using get_or_create and select_related
How to create a django model record using get_or_create and select_related

Time:04-11

I have a class like below:

class GroupProduct(models.Model):
   product = models.ForeignKey(
           'myapp.Products'
           related_name='myapp_group_product')


   @classmethod
   def create_group_product(cls, p_id, product_id):
       cls.objects.get_or_create(id=p_id, defaults=dict(product=product_id).select_related('product')

So I expect it creates a record in the table with the following params, however it doesn't.

GP = GroupProduct()
GP.create_group_product(3, 225)

It says it product must be a myapp.Products instance. Is there any way to use select_related in this way rather than doing a seprate query and hit the database?

CodePudding user response:

You can work with:

cls.objects.select_related('product').get_or_create(
    id=p_id,
    defaults={'product_id': product_id}
)

If the item already exists, it will fetch the product data with the same query. If it does not (yet) exists, it will make an insert query, and you can then fetch the Product in a second query, since it will not make any fetch query and thus simply create a record and return a cls object.

  • Related