Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6578659
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 25, 20262026-05-25T15:47:56+00:00 2026-05-25T15:47:56+00:00

I have a model that looks like this and stores data as key-value pairs.

  • 0

I have a model that looks like this and stores data as key-value pairs.

class Setting(models.Model):
    company = models.ForeignKey(
        Company
    )
    name = models.CharField(
        null=False, max_length=255
    )
    value= models.CharField(
        null=False, max_length=255
    )

I have a custom Manager on this Model which overrides the get method. When the queries my Model like Settings.objects.get(company=1), I use my over-ridden get method to execute a self.objects.filter(company=1) which returns a list of objects. Can I generate one single custom QuerySet which has all the key-value pairs as fields.

Example:

If the data in my Model was like this:

company  name    value
-------  ----    -----
1        theme   custom
1        mode    fast
1        color   green

I’d like to return a query set that would be pivoted like so when someone executed Settings.objects.get(company=1):

company  theme    mode     color
------   -----    ----     -----
1        custom   fast     green

I’ve tried to be verbose but do let me know if I should explain better. I’m not sure if the Django Models allow this scenario.

Thank you everyone.


Edit: Using Proxy models

Is this something I could accomplish using Proxy Models i.e. having a base model to store the key value fields and custom proxy model with normal get and save method?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-25T15:47:57+00:00Added an answer on May 25, 2026 at 3:47 pm

    Here’s how I did it.

    I needed to do this because I had a Model that stored information as key value pairs and I needed to build a ModelForm on that Model but the ModelForm should display the key-value pairs as fields i.e. pivot the rows to columns. By default, the get() method of the Model always returns a Model instance of itself and I needed to use a custom Model. Here’s what my key-value pair model looked like:

    class Setting(models.Model):
        domain = models.ForeignKey(Domain)
        name = models.CharField(null=False, max_length=255)
        value = models.CharField(null=False, max_length=255)
    
        objects = SettingManager()
    

    I built a custom manager on this to override the get() method:

    class SettingManager(models.Manager):
    
        def get(self, *args, **kwargs):
            from modules.customer.proxies import *
            from modules.customer.models import *
    
            object = type('DomainSettings', (SettingProxy,), {'__module__' : 'modules.customer'})()
            for pair in self.filter(*args, **kwargs): setattr(object, pair.name, pair.value)
    
            setattr(object, 'domain', Domain.objects.get(id=int(kwargs['domain__exact'])))
            return object
    

    This Manager would instantiate an instance of this abstract model. (Abstract models don’t have tables so Django doesn’t throw up errors)

    class SettingProxy(models.Model):
    
        domain = models.ForeignKey(Domain, null=False, verbose_name="Domain")
        theme = models.CharField(null=False, default='mytheme', max_length=16)
        message = models.CharField(null=False, default='Waddup', max_length=64)
    
        class Meta:
            abstract = True
    
        def __init__(self, *args, **kwargs):
            super(SettingProxy, self).__init__(*args, **kwargs)
            for field in self._meta.fields:
                if isinstance(field, models.AutoField):
                    del field
    
        def save(self, *args, **kwargs):
            with transaction.commit_on_success():
                Setting.objects.filter(domain=self.domain).delete()
    
                for field in self._meta.fields:
                    if isinstance(field, models.ForeignKey) or isinstance(field, models.AutoField):
                        continue
                    else:
                        print field.name + ': ' + field.value_to_string(self)
                        Setting.objects.create(domain=self.domain,
                            name=field.name, value=field.value_to_string(self)
                        )
    

    This proxy has all the fields that I’d like display in my ModelFom and store as key-value pairs in my model. Now if I ever needed to add more fields, I could simply modify this abstract model and not have to edit the actual model itself. Now that I have a model, I can simply build a ModelForm on it like so:

    class SettingsForm(forms.ModelForm):
    
        class Meta:
            model = SettingProxy
            exclude = ('domain',)
    
        def save(self, domain, *args, **kwargs):
            print self.cleaned_data
            commit = kwargs.get('commit', True)
            kwargs['commit'] = False
            setting = super(SettingsForm, self).save(*args, **kwargs)
            setting.domain = domain
            if commit:
                setting.save()
            return setting
    

    I hope this helps. It required a lot of digging through the API docs to figure this out.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a rails model that looks something like this: class Recipe < ActiveRecord::Base
I have a class in my domain model root that looks like this: namespace
Newbie question. I have Django models that look like this: class Video(models.Model): uploaded_by =
I have a model that is something like this: class Input(models.Model): details = models.CharField(max_length=1000)
I have three models that look something like this: class Bucket < ActiveRecord::Base has_many
I have an XML document that looks like this: <?xml version=1.0 encoding=utf-8?> <Schema Namespace=EDIManagement.Models.Store
I have a ListView setup in details mode that looks like this: When the
I have methods in all of my models that look like this: def formatted_start_date
Generally, MVC frameeworks have a structure that looks something like: /models /views /controllers /utils
I have three model classes that look as below: class Model(models.Model): model = models.CharField(max_length=20,

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.