Django - Use model fields part in a create or update query

Viewed 154

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={……}
)
1 Answers

Not sure this is what you are looking for but if you used multi-table inheritance you could achieve the following

class ShelfPosition(models.Model):
    shelf_code = models.CharField(max_length=10)
    row = models.IntegerField()
    column = models.IntegerField()

    class Meta:
        unique_together = ("shelf_code", "row", "column")

class Item(ShelfPosition):
    name = models.CharField(max_length=255)

item, created = Item.objects.get_or_create(
    shelf_code="BF6",
    row=88,
    column=1,
    defaults={
       "name": "Spam",
    }
)

You'd just have to make sure to pass keep_parents=True when calling item.delete() if you want to preserve the ShelfPosition row as the default MTI behavior is to delete the whole ancestor chain.

Related