Question

I have a model with a number of settings:

class SettingsProfile(models.Model):

  video_enabled = BooleanField()
  audio_enabled = BooleanField()
  sensors_enabled = BooleanField()
  reporting Enabled = BooleanField()

If a user has already created a SettingsProfile model, things are fine, we can query the /v1/settingsprofiles/ endpoint and get what we need.

However, if a settings profile does not exist that matches my query (the given user hasn't created it yet), I want to return a SettingsProfile resource with some default settings filled out. Note that I don't want to CREATE a SettingsProfile row in the DB, I just want to display what LOOKS like a SettingsProfile resource but is really just displaying some defaults.

Is there some kind of way to coax Django into creating what looks like a model but hasn't been saved to the DB and getting Tastypie to use that to supply the client when they make a GET request for a SettingsProfile that does not yet exist?

Was it helpful?

Solution

class SettingsProfile(models.Model):
    video_enabled = BooleanField(default=True)
    audio_enabled = BooleanField(default=False)
    sensors_enabled = BooleanField(default=True)
    reporting_enabled = BooleanField(default=False)

.

try:
    settings_profile = SettingsProfile.objects.get(user=user)
except SettingsProfile.DoesNotExist:
    settings_profile = SettingsProfile()  # A new one with default values
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top