Search code examples
djangostate-machinedjango-fsm

Using django-fsm to determine the state of an object


How do I get the current state of a database item using django-fsm. I have tried get_state() but it returns a null value.

Here is my code:

from django.db import models
from django_fsm import FSMField, transition

STATES = ("Open", "In Progress", "Re Opened", "Done", "Closed")
STATES = list(zip(STATES, STATES))

class Ticket(models.Model):
    title = models.CharField(max_length=40)
    state = FSMField(default=STATES[0], choices=STATES)

Is there a way of getting the state field using django-fsm library. Also, how do I get the available state transitions using the model methods.


Solution

  • You can get the value of the stat field by accessing it like a normal field:

    ticket.state
    

    If you want to get the display friendly version, FSMField works like any CharField(choices=[]) field using:

    ticket.get_state_display()
    

    You can get all of the available transitions by calling:

    ticket.get_available_state_transitions()
    

    You didn't define any transitions on your model so this call would not return anything at the moment.