Opened 15 years ago
Closed 15 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: | no | UI/UX: | no |
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})
Note:
See TracTickets
for help on using tickets.
This is #5535.