0

I'd like to have a model field that will return the latest related of another model.

An example-

class Thing(models.Model):
  name = models.CharField(max_length=200)
  state = models.ForeignKey(State, query=latest) #pure fantasy
class State(models.Model):
  change = models.DateTimeField(auto_now_add=True)
  thing = models.ForeignKey(Thing)

Assume that the model class State has a many to one relationship to Thing.

given- some_thing = Thing.object.all()[0]

I want some_thing.state to be the instance of State that has the most recent State.change value for the instance Thing that I have in hand.

I'd like to specify at the Django Model level an instance variable that does what I've described above. I can think of two ways to do this, but neither is at this level:

  1. at the actual DB level -- create a view and turn off django db syncing (http://stackoverflow.com/questions/507795/can-i-use-a-database-view-as-a-model-in-django)
  2. the view level -- when I create new State row manually set that row to the related Thing.state instance.
hewsonism
  • 424
  • 4
  • 11

1 Answers1

0

You cannot have a database level dynamic foreign key. You can, however, have a property or a method that captures your item for you:

class Thing(models.Model):
    name = models.CharField(max_length=200)

    @property
    def state(self):
        return State.objects.latest('change')

class State(models.Model):
    change = models.DateTimeField(auto_now_add=True)
    thing = models.ForeignKey(Thing)
drewman
  • 1,565
  • 11
  • 15