Code

Opened 4 years ago

Closed 4 years ago

#13915 closed (duplicate)

getting and creating with get_or_create behave differently when using a foreign key

Reported by: KyleMac Owned by: nobody
Component: Database layer (models, ORM) Version: 1.2
Severity: Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: UI/UX:

Description

Using the following models:

class Product(models.Model):
    name = models.CharField()

class Stat(models.Model):
    product = models.ForeignKey(Product)
    value = models.PositiveIntegerField()

If you do the following and the row doesn't exist:

Stat.objects.get_or_create(product__id=1, defaults={'value': 0})

you will get an exception that product_id cannot be null (i.e. the create is failing).

However, if you do the following instead:

Stat.objects.get_or_create(product_id=1, defaults={'value': 0})

you get an exception that product_id cannot be resolved to a field (i.e. the get is failing).

The solution is to do something like:

Stat.objects.get_or_create(product=Product(id=1), defaults={'value': 0})

Attachments (0)

Change History (1)

comment:1 Changed 4 years ago by kmtracey

  • Needs documentation unset
  • Needs tests unset
  • Patch needs improvement unset
  • Resolution set to duplicate
  • Status changed from new to closed

This is #5535.

Add Comment

Modify Ticket

Change Properties
<Author field>
Action
as closed
as The resolution will be set. Next status will be 'closed'
The resolution will be deleted. Next status will be 'new'
Author


E-mail address and user name can be saved in the Preferences.

 
Note: See TracTickets for help on using tickets.