Given the following models in a Django 2.2 app:
class ShelfPosition(models.Model):
shelf_code = models.CharField(max_length=10)
row = models.IntegerField()
column = models.IntegerField()
class Meta:
constraints = [
models.UniqueConstraint(fields=["shelf_number", "row", "column"], name="shelfpos_unique")
]
class Item(models.Model):
name = models.CharField(max_length=255)
position = models.OneToOneField(to=ShelfPosition, on_delete=models.SET_NULL, primary_key=True)
I rely on Django's lookup feature to filter on Item objects depending on some ShelfPosition fields:
Item.objects.filter(position__shelf_code="BF4")
Is there any way I could implement a similar lookup functionality such as described above when using get_or_create or update_or_create?
item, created = Item.objects.get_or_create(
position__shelf_code="BF6",
position__row=88,
position__column=1,
defaults={……}
)
I find it less verbose than the following, even if with this example it's not really relevant:
item, created = Item.objects.get_or_create(
position = Position.objects.get_or_create(
shelf_code="BF6",
row=88,
column=1
),
defaults={……}
)