Search Results

Search found 15231 results on 610 pages for 'presentation model'.

Page 34/610 | < Previous Page | 30 31 32 33 34 35 36 37 38 39 40 41  | Next Page >

  • Two Tables Serving as one Model in Rails

    - by matsko
    Is is possible in rails to setup on model which is dependant on a join from two tables? This would mean that for the the model record to be found/updated/destroyed there would need to be both records in both database tables linked together in a join. The model would just be all the columns of both tables wrapped together which may then be used for the forms and so on. This way when the model gets created/updated it is just one form variable hash that gets applied to the model? Is this possible in Rails 2 or 3?

    Read the article

  • ASP.NET MVC - Disable Html Helper control using boolean value from Model

    - by The Matt
    I am outputting a textbox to the page using the Html helpers. I want to add the disabled attribute dynamically based on whether or not a boolean value in my model is true or false. My model has a method that returns a boolean value: <% =Model.IsMyTextboxEnabled() %> I currently render the textbox like follows, but I want to now enabled or disable it: <% =Html.TextBox("MyTextbox", Model.MyValuenew { id = "MyTextbox", @class = "MyClass" })%> If the return value of Model.IsMyTextboxEnabled() == true I want the following to be output: <input class="MyClass" id="MyTextbox" name="MyTextbox" type="text" value="" /> If it == false, I want it to output as: <input class="MyClass" id="MyTextbox" name="MyTextbox" type="text" value="" disabled /> What is the cleanest way to do this?

    Read the article

  • JavaFX - question regarding binding button's disabled state

    - by jamiebarrow
    I'm trying to create a dummy application that maintains a list of tasks. For now, all I'm trying to do is add to the list. I enter a task name in a text box, click on the add task button, and expect the list to be updated with the new item and the task name input to be cleared. I only want to be able to add tasks if the task name is not empty. The below code is my implementation, but I have a question regarding the binding. I'm binding the textbox's text variable to a string in my view model, and the button's disable variable to a boolean in my view model. I have a trigger to update the disabled state when the task name changes. When the binding of the task name happens the boolean is updated accordingly, but the button still appears disabled. But then when I mouse over the button, it becomes enabled. I believe this is due to JavaFX 1.3's binding being lazy - only updates the bound variable when it is read. Also, when I've added the task, I clear the task name in the model, but the textbox's text doesn't change - even though I'm using bind with inverse. Is there a way to make the textbox's text and the button's disabled state update automatically via the binding as I was expecting? Thanks, James AddTaskViewModel.fx: package jamiebarrow; import java.lang.System; public class AddTaskViewModel { function logChange(prop:String,oldValue,newValue):Void { println("{System.currentTimeMillis()} : {prop} [{oldValue}] to [{newValue}] "); } public var newTaskName: String on replace old { logChange("newTaskName",old,newTaskName); isAddTaskDisabled = (newTaskName == null or newTaskName.trim().length() == 0); }; public var isAddTaskDisabled: Boolean on replace old { logChange("isAddTaskDisabled",old,isAddTaskDisabled); }; public var taskItems = [] on replace old { logChange("taskItems",old,taskItems); }; public function addTask() { insert newTaskName into taskItems; newTaskName = ""; } } Main.fx: package jamiebarrow; import javafx.scene.control.Button; import javafx.scene.control.TextBox; import javafx.scene.control.ListView; import javafx.scene.Scene; import javafx.scene.layout.VBox; import javafx.stage.Stage; import javafx.scene.layout.HBox; def viewModel = AddTaskViewModel{}; var txtName: TextBox = TextBox { text: bind viewModel.newTaskName with inverse onKeyTyped: onKeyTyped }; function onKeyTyped(event): Void { txtName.commit(); // ensures model is updated cmdAddTask.disable = viewModel.isAddTaskDisabled;// the binding only occurs lazily, so this is needed } var cmdAddTask = Button { text: "Add" disable: bind viewModel.isAddTaskDisabled with inverse action: onAddTask }; function onAddTask(): Void { viewModel.addTask(); } var lstTasks = ListView { items: bind viewModel.taskItems with inverse }; Stage { scene: Scene { content: [ VBox { content: [ HBox { content: [ txtName, cmdAddTask ] }, lstTasks ] } ] } }

    Read the article

  • Can I bind multiple forms to a single model using the default model binder?

    - by MedicineMan
    I have a complex page with several forms on it. The page is divided into sections, and each section has a continue button on it. The page is bound to a pageViewModel, each section addresses a different set of properties on the model. The continue button makes an ajax call to the controller, and the model binder binds it appropriately to the appropriate sections of the model. The section is refreshed appropriately. Finally, I would like to have a save button at the bottom of the page that takes all the forms, and binds all of the forms to the model. The model, at this point has all of the properties filled out, and can be processed accordingly. Can I accomplish this by some ASP MVC magic?

    Read the article

  • Quering distinct values throught related model

    - by matheus.emm
    Hi! I have a simple one-to-many (models.ForeignKey) relationship between two of my model classes: class TeacherAssignment(models.Model): # ... some fields year = models.CharField(max_length=4) class LessonPlan(models.Model): teacher_assignment = models.ForeignKey(TeacherAssignment) # ... other fields I'd like to query my database to get the set of distinct years of TeacherAssignments related to at least one LessonPlan. I'm able to get this set using Django query API if I ignore the relation to LessonPlan: class TeacherAssignment(models.Model): # ... model's fields def get_years(self): year_values = self.objects.all().values_list('year').distinct().order_by('-year') return [yv[0] for yv in year_values if len(yv[0]) == 4] Unfortunately I don't know how to express the condition that the TeacherAssignment must be related to at least one LessonPlan. Any ideas how I'd be able to write the query? Thanks in advance.

    Read the article

  • asp.net mvc custom model binding in an update entity scenario

    - by mctayl
    Hi I have a question about model binding. Imagine you have an existing database entity displayed in a form and you'd like to edit some details, some properties eg createddate etc are not bound to the form, during model binding, these properties are not assigned to the model as they are not on the http post data or querystrong etc, hence their properties are null. In my controller method for update , Id just like to do public ActionResult Update( Entity ent) { //Save changes to db } but as some properties are null in ent, they override the existing database fields which are not part of the form post data, What is the correct way to handle this? Ive tried hidden fields to hold the data, but model binding does not seem to assign hidden fields to the model. Any suggestions would be appreciated

    Read the article

  • Configuration and Model-View

    - by HH
    I am using the Model-View pattern on a small application I'm writing. Here's the scenario: The model maintains a list of directories from where it can extract the data that it needs. The View has a Configuration or a Setting dialog where the user can modify this list of directories (the dialog has a JList displaying the list in addition to add and remove buttons). I need some advice from the community: The View needs to communicate these changes to the model. I thought first of adding to the model these methods: addDirectory() and removeDirectory(). But I am trying to limit the number of methods (or channels) that the View can use to communicate with and manipulate the model. Is there any good practice for this? Thank you.

    Read the article

  • Django: Extending User Model - Inline User fields in UserProfile

    - by Jack Sparrow
    Is there a way to display User fields under a form that adds/edits a UserProfile model? I am extending default Django User model like this: class UserProfile(models.Model): user = models.OneToOneField(User, unique=True) about = models.TextField(blank=True) I know that it is possible to make a: class UserProfileInlineAdmin(admin.TabularInline): and then inline this in User ModelAdmin but I want to achieve the opposite effect, something like inverse inlining, displaying the fields of the model pointed by the OneToOne Relationship (User) in the page of the model defining the relationship (UserProfile). I don't care if it would be in the admin or in a custom view/template. I just need to know how to achieve this. I've been struggling with ModelForms and Formsets, I know the answer is somewhere there, but my little experience in Django doesn't allow me to come up with the solution yet. A little example would be really helpful!

    Read the article

  • Rails: Ajax-enabled form without a model object

    - by Caffeine Coma
    I'm new to Rails and having a hard time figuring out how to create a form that submits over Ajax without having a corresponding model object. My use case is a simple form that collects an email address and sends it an email; there's nothing to be persisted, so no model. In cases where I do have a model, I've had success with form_for(@model, remote: true). I can't seem to find the right helper for the case where there is no model. I tried form_tag(named_path, remote: true) and that works, but does not use Ajax. Pointers to an example with an example with a proper controller, .html.erb and routes.rb would be really appreciated.

    Read the article

  • Deleting inline model in Django admin

    - by Overclocked
    I am trying to use Django admin to remove an inline model. I get an error saying [u'Select a valid choice. That choice is not one of the available choices.'] I check the location where the exception is raised. It seems like the inline model was removed, then a form validation happened on the parent model with the deleted inline model still as value of the form. That caused the failure. In my admin model, I had a save_formset method defined, that called formset.save(commit=False). Is the commit=False not telling Django to not delete the related models? Thanks.

    Read the article

  • Sql Server differential backup : Simple vs Full recovery model

    - by MaxiWheat
    I need to better understand the backup process under SQL Server 2008. Since drive space is a kind of matter for us and we want to have a better disaster recovery solution, I decided that we will implement differential backups throughout the day (every hour). Am I right to think that if I keep the recovery model of my databases to Simple, the differential backup will be almost the same size as Full Backup (too big to make one every hour) ? I already tried to switch to Full recovery and it seemed to have fixed the issue (differential backups were way smaller). I heard that the recovery model must be set to Full to use Log backups (to the minute recovery etc., but we don't need that) but never about differential backups. So, is the recovery model really having an impact on differential backups or am I missing something ? Thank you

    Read the article

  • How to understand cpu family/model/stepping fields in /proc/cpuinfo

    - by Victor Sorokin
    I have following in cpuinfo: processor : 0 vendor_id : AuthenticAMD cpu family : 15 model : 107 model name : AMD Athlon(tm) 64 X2 Dual Core Processor 5600+ stepping : 2 According to Wikipedia page there are two kinds of 5600+ -- one of 90nm technology, another of 65nm. How can I understand which one I have? There seem to be no direct correspondence between contents of cpuinfo and info on Wikipedia page. AMD site seems to use some other naming scheme for processors too. How can I map values of family, model and stepping from cpuinfo to the data available on Wikipedia/AMD?

    Read the article

  • How to understand cpu family/model/stepping fields in /proc/cpuinfo [closed]

    - by Victor Sorokin
    I have following in cpuinfo: processor : 0 vendor_id : AuthenticAMD cpu family : 15 model : 107 model name : AMD Athlon(tm) 64 X2 Dual Core Processor 5600+ stepping : 2 According to Wikipedia page there are two kinds of 5600+ -- one of 90nm technology, another of 65nm. How can I understand which one I have? There seem to be no direct correspondence between contents of cpuinfo and info on Wikipedia page. AMD site seems to use some other naming scheme for processors too. How can I map values of family, model and stepping from cpuinfo to the data available on Wikipedia/AMD?

    Read the article

  • Is it a "pattern smell" to put getters like "FullName" or "FormattedPhoneNumber" in your model?

    - by DanM
    I'm working on an ASP.NET MVC app, and I've been getting into the habit of putting what seem like helpful and convenient getters into my model/entity classes. For example: public class Member { public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string PhoneNumber { get; set; } public string FullName { get { return FirstName + " " + LastName; } } public string FormattedPhoneNumber { get { return "(" + PhoneNumber.Substring(0, 3) + ") " + PhoneNumber.Substring(3, 3) + "-" + PhoneNumber.Substring(6); } } } I'm wondering people think about the FullName and FormattedPhoneNumber getters. They make it very easy to create standardized data formats throughout the app, and they seem to save a lot of repeated code, but it could definitely be argued that data format is something that should be handled in mapping from model to view-model. In fact, I was originally applying these data formats in my service layer where I do my mapping, but it was becoming a burden to constantly have to write formatters then apply them in many different places. E.g., I use "Full Name" in most views, and having to type something like model.FullName = MappingUtilities.GetFullName(entity.FirstName, entity.LastName); all over the place seemed a lot less elegant than just typing model.FullName = entity.FullName (or, if you use something like AutoMapper, potentially not typing anything at all). So, where do you draw the line when it comes to data formatting. Is it "okay" to do data formatting in your model or is that a "pattern smell"? Note: I definitely do not have any html in my model. I use html helpers for that. I'm strictly talking about formatting or combining data (and especially data that is frequently used).

    Read the article

  • Specifying different initial values for fields in inherited models (django)

    - by Shawn Chin
    Question : What is the recommended way to specify an initial value for fields if one uses model inheritance and each child model needs to have different default values when rendering a ModelForm? Take for example the following models where CompileCommand and TestCommand both need different initial values when rendered as ModelForm. # ------ models.py class ShellCommand(models.Model): command = models.Charfield(_("command"), max_length=100) arguments = models.Charfield(_("arguments"), max_length=100) class CompileCommand(ShellCommand): # ... default command should be "make" class TestCommand(ShellCommand): # ... default: command = "make", arguments = "test" I am aware that one can used the initial={...} argument when instantiating the form, however I would rather store the initial values within the context of the model (or at least within the associated ModelForm). My current approach What I'm doing at the moment is storing an initial value dict within Meta, and checking for it in my views. # ----- forms.py class CompileCommandForm(forms.ModelForm): class Meta: model = CompileCommand initial_values = {"command":"make"} class TestCommandForm(forms.ModelForm): class Meta: model = TestCommand initial_values = {"command":"make", "arguments":"test"} # ------ in views FORM_LOOKUP = { "compile": CompileCommandFomr, "test": TestCommandForm } CmdForm = FORM_LOOKUP.get(command_type, None) # ... initial = getattr(CmdForm, "initial_values", {}) form = CmdForm(initial=initial) This feels too much like a hack. I am eager for a more generic / better way to achieve this. Suggestions appreciated. Other attempts I have toyed around with overriding the constructor for the submodels: class CompileCommand(ShellCommand): def __init__(self, *args, **kwargs): kwargs.setdefault('command', "make") super(CompileCommand, self).__init__(*args, **kwargs) and this works when I try to create an object from the shell: >>> c = CompileCommand(name="xyz") >>> c.save() <CompileCommand: 123> >>> c.command 'make' However, this does not set the default value when the associated ModelForm is rendered, which unfortunately is what I'm trying to achieve. Update 2 (looks promising) I now have the following in forms.py which allow me to set Meta.default_initial_values without needing extra code in views. class ModelFormWithDefaults(forms.ModelForm): def __init__(self, *args, **kwargs): if hasattr(self.Meta, "default_initial_values"): kwargs.setdefault("initial", self.Meta.default_initial_values) super(ModelFormWithDefaults, self).__init__(*args, **kwargs) class TestCommandForm(ModelFormWithDefaults): class Meta: model = TestCommand default_initial_values = {"command":"make", "arguments":"test"}

    Read the article

  • How with lambda function in MVC3

    - by doogdeb
    I have a model which contains view models for each view. This model is held in session and is initialised when application starts. I need to be able to populate a field from one view model with the value from another so have used a lambda function. Below is my model. I am using a lambda so that when I get Test2.MyProperty it will use the FunctionTestProperty to retrieve the value from Test1.TestProperty. public class Model { public Model() { Test1 = new Test1() Test2 = new Test2(FunctionTestProperty () => Test1.TestProperty) } } public class Test1 { public string TestProperty { get; set; } } public class Test2 { public Test2() : this (() => string.Empty) {} public Test2(Func<string> functionTestProperty) { FunctionTestProperty = functionTestProperty; } public Func<string> FunctionTestProperty { get; set; } public string MyProperty { get{ return FunctionTestProperty() ?? string.Empty; } } } This works perfectly when I first run the application and navigate from Test1 to Test2; I can see that when I get the value for MyProperty it calls back to Model constructor and retrieves the Test1.TestProperty value. However when I then submit the form (Test2) it calls the default constructor which sets it to string.Empty. So if I go back to Test1 and back to Test2 again it always then calls the Test2 default constructor. Does anyone know why this works when first running the application but not after the view is submitted, or if I have made an obvious mistake?

    Read the article

  • Best way to return result from business layer to presentation layer when using LINQ-to-SQL

    - by samsur
    I have a business layer that has DTOs that are used in the presentation layer. This application uses entity framework. Here is an example of a class called RoleDTO: public class RoleDTO { public Guid RoleId { get; set; } public string RoleName { get; set; } public string RoleDescription { get; set; } public int? OrganizationId { get; set; } } In the BLL I want to have a method that returns a list of DTO. I would like to know which is the better approach: returning IQueryable or list of DTOs. Although I feel that returning IQueryable is not a good idea because the connection needs to be open. Here are the 2 different methods using the different approaches: First approach public class RoleBLL { private servicedeskEntities sde; public RoleBLL() { sde = new servicedeskEntities(); } public IQueryable<RoleDTO> GetAllRoles() { IQueryable<RoleDTO> role = from r in sde.Roles select new RoleDTO() { RoleId = r.RoleID, RoleName = r.RoleName, RoleDescription = r.RoleDescription, OrganizationId = r.OrganizationId }; return role; } Note: in the above method the DataContext is a private attribute and set in the constructor, so that the connection stays opened. Second approach public static List<RoleDTO> GetAllRoles() { List<RoleDTO> roleDTO = new List<RoleDTO>(); using (servicedeskEntities sde = new servicedeskEntities()) { var roles = from pri in sde.Roles select new { pri.RoleID, pri.RoleName, pri.RoleDescription }; //Add the role entites to the DTO list and return. This is necessary as anonymous types can be returned acrosss methods foreach (var item in roles) { RoleDTO roleItem = new RoleDTO(); roleItem.RoleId = item.RoleID; roleItem.RoleDescription = item.RoleDescription; roleItem.RoleName = item.RoleName; roleDTO.Add(roleItem); } return roleDTO; } } Please let me know, if there is a better approach.

    Read the article

  • Microsoft Press Deal of the Day - 13/April/2012 - Building Enterprise Applications with Windows® Presentation Foundation and the MVVM Pattern

    - by TATWORTH
    Today's deal of the day from Microsoft Press at http://shop.oreilly.com/product/0790145309686.do is Building Enterprise Applications with Windows® Presentation Foundation and the MVVM Pattern"Simplify and improve business application development by applying the MVVM pattern to Windows Presentation Foundation (WPF) and Microsoft® Silverlight® 4. With this hands-on guide, you'll use MVVM with data binding, commands, and behaviors to create user interfaces loosely coupled to business logic. MVVM is ideal for .NET developers working with WPF and Silverlight—whether or not you have experience building enterprise applications."

    Read the article

  • ASP.NET MVC - Html.DropDownList - Value not set via ViewData.Model

    - by chrisb
    Have just started playing with ASP.NET MVC and have stumbled over the following situation. It feels a lot like a bug but if its not, an explanation would be appreciated :) The View contains pretty basic stuff <%=Html.DropDownList("MyList", ViewData["MyListItems"] as SelectList)%> <%=Html.TextBox("MyTextBox")%> When not using a model, the value and selected item are set as expected: //works fine public ActionResult MyAction(){ ViewData["MyListItems"] = new SelectList(items, "Value", "Text"); //items is an ienumerable of {Value="XXX", Text="YYY"} ViewData["MyList"] = "XXX"; //set the selected item to be the one with value 'XXX' ViewData["MyTextBox"] = "ABC"; //sets textbox value to 'ABC' return View(); } But when trying to load via a model, the textbox has the value set as expected, but the dropdown doesnt get a selected item set. //doesnt work public ActionResult MyAction(){ ViewData["MyListItems"] = new SelectList(items, "Value", "Text"); //items is an ienumerable of {Value="XXX", Text="YYY"} var model = new { MyList = "XXX", //set the selected item to be the one with value 'XXX' MyTextBox = "ABC" //sets textbox value to 'ABC' } return View(model); } Any ideas? My current thoughts on it are that perhaps when using a model, we're restricted to setting the selected item on the SelectList constructor instead of using the viewdata (which works fine) and passing the selectlist in with the model - which would have the benefit of cleaning the code up a little - I'm just wondering why this method doesnt work.... Many thanks for any suggestions

    Read the article

  • ASP.net MVC - Update Model on complex models

    - by ludicco
    Hi there, I'm struggling myself trying to get the contents of a form which is a complex model and then update the model with that complex model. My account model has many individuals [AcceptVerbs(HttpVerbs.Post)] public ActionResult OpenAnAccount(string area,[Bind(Exclude = "Id")]Account account, [Bind(Prefix="Account.Individuals")] EntitySet<Individual> individuals){ var db = new DB(); account.individuals = invdividuals; db.Accounts.InsertOnSubmit(account); db.SubmitChanges(); } So it works nicely for adding new Records, but not for update them like: [AcceptVerbs(HttpVerbs.Post)] public ActionResult OpenAnAccount(string area,[Bind(Exclude = "Id")]Account account, [Bind(Prefix="Account.Individuals")] EntitySet<Individual> individuals){ var db = new DB(); var record = db.Accounts.Single(a => a.Reference == area); account.individuals = invdividuals; try{ UpdateModel(record, account); // I can't convert account ToValueProvider() db.SubmitChanges(); } catch{ return ... //Error Message } } My problem is being how to use UpdateModel with the account model since it's not a FormCollection. How can I convert it? How can I use ToValueProvider with a complex model? I hope I was clear enough Thanks a lot :)

    Read the article

  • Django model operating on a queryset

    - by jmoz
    I'm new to Django and somewhat to Python as well. I'm trying to find the idiomatic way to loop over a queryset and set a variable on each model. Basically my model depends on a value from an api, and a model method must multiply one of it's attribs by this api value to get an up-to-date correct value. At the moment I am doing it in the view and it works, but I'm not sure it's the correct way to achieve what I want. I have to replicate this looping elsewhere. Is there a way I can encapsulate the looping logic into a queryset method so it can be used in multiple places? I have this atm (I am using django-rest-framework): class FooViewSet(viewsets.ModelViewSet): model = Foo serializer_class = FooSerializer bar = # some call to an api def get_queryset(self): # Dynamically set the bar variable on each instance! foos = Foo.objects.filter(baz__pk=1).order_by('date') for item in foos: item.needs_bar = self.bar return items I would think something like so would be better: def get_queryset(self): bar = # some call to an api # Dynamically set the bar variable on each instance! return Foo.objects.filter(baz__pk=1).order_by('date').set_bar(bar) I'm thinking the api hit should be in the controller and then injected to instances of the model, but I'm not sure how you do this. I've been looking around querysets and managers but still can't figure it out nor decided if it's the best method to achieve what I want. Can anyone suggest the correct way to model this with django? Thanks.

    Read the article

  • CakePHP belongsTo relationship with a variable 'model' field.

    - by gomezuk
    I've got a problem with a belongsTo relationship in CakePHP. I've got an "Action" model that uses the "actions" table and belongs to one of two other models, either "Transaction" or "Tag". The idea being that whenever a user completes a transaction or adds a tag, the action model is created to keep a log of it. I've got that part working, whenever a Transaction or Tag is saved, the aftersave() method also adds an Action record. The problem comes when I try to do a find('all') on the Action model, the related Transaction or Tag record is not being returned. actions: id model model_id created I thought I could use the "conditions" parameter in the belongsTo relationship like this: <?php class Action extends AppModel { var $name = 'Action'; var $actsAs = array('Containable'); var $belongsTo = array( 'Transaction' => array( 'foreignKey' => 'model_id', 'conditions' => array("Action.model"=>"Transaction") ), 'User' => array( 'fields' => array('User.username') ), 'Recommendation' => array( 'conditions' => array("Action.model"=>"Recommendation"), 'foreignKey' => 'model_id' ) ); } ?> But that doesn't work. Am I missing something here, are my relationships wrong (I suspect so)? After Googling this problem I cam across something called Polymorphic Behaviour but I'm not sure this will help me.

    Read the article

  • JSON Serialization of a Django inherited model

    - by Simon Morris
    Hello, I have the following Django models class ConfigurationItem(models.Model): path = models.CharField('Path', max_length=1024) name = models.CharField('Name', max_length=1024, blank=True) description = models.CharField('Description', max_length=1024, blank=True) active = models.BooleanField('Active', default=True) is_leaf = models.BooleanField('Is a Leaf item', default=True) class Location(ConfigurationItem): address = models.CharField(max_length=1024, blank=True) phoneNumber = models.CharField(max_length=255, blank=True) url = models.URLField(blank=True) read_acl = models.ManyToManyField(Group, default=None) write_acl = models.ManyToManyField(Group, default=None) alert_group= models.EmailField(blank=True) The full model file is here if it helps. You can see that Company is a child class of ConfigurationItem. I'm trying to use JSON serialization using either the django.core.serializers.serializer or the WadofStuff serializer. Both serializers give me the same problem... >>> from cmdb.models import * >>> from django.core import serializers >>> serializers.serialize('json', [ ConfigurationItem.objects.get(id=7)]) '[{"pk": 7, "model": "cmdb.configurationitem", "fields": {"is_leaf": true, "extension_attribute_10": "", "name": "", "date_modified": "2010-05-19 14:42:53", "extension_attribute_11": false, "extension_attribute_5": "", "extension_attribute_2": "", "extension_attribute_3": "", "extension_attribute_1": "", "extension_attribute_6": "", "extension_attribute_7": "", "extension_attribute_4": "", "date_created": "2010-05-19 14:42:53", "active": true, "path": "/Locations/London", "extension_attribute_8": "", "extension_attribute_9": "", "description": ""}}]' >>> serializers.serialize('json', [ Location.objects.get(id=7)]) '[{"pk": 7, "model": "cmdb.location", "fields": {"write_acl": [], "url": "", "phoneNumber": "", "address": "", "read_acl": [], "alert_group": ""}}]' >>> The problem is that serializing the Company model only gives me the fields directly associated with that model, not the fields from it's parent object. Is there a way of altering this behaviour or should I be looking at building a dictionary of objects and using simplejson to format the output? Thanks in advance ~sm

    Read the article

  • Implementing Model-level caching

    - by Byron
    I was posting some comments in a related question about MVC caching and some questions about actual implementation came up. How does one implement a Model-level cache that works transparently without the developer needing to manually cache, yet still remains efficient? I would keep my caching responsibilities firmly within the model. It is none of the controller's or view's business where the model is getting data. All they care about is that when data is requested, data is provided - this is how the MVC paradigm is supposed to work. (Source: Post by Jarrod) The reason I am skeptical is because caching should usually not be done unless there is a real need, and shouldn't be done for things like search results. So somehow the Model itself has to know whether or not the SELECT statement being issued to it worthy of being cached. Wouldn't the Model have to be astronomically smart, and/or store statistics of what is being most often queried over a long period of time in order to accurately make a decision? And wouldn't the overhead of all this make the caching useless anyway? Also, how would you uniquely identify a query from another query (or more accurately, a resultset from another resultset)? What about if you're using prepared statements, with only the parameters changing according to user input? Another poster said this: I would suggest using the md5 hash of your query combined with a serialized version of your input arguments. This would require twice the number of serialization options. I was under the impression that serialization was quite expensive, and for large inputs this might be even worse than just re-querying. And is the minuscule chance of collision worth worrying about? Conceptually, caching in the Model seems like a good idea to me, but it seems in practicality the developer should have direct control over caching and write it into the controller. Thoughts/ideas? Edit: I'm using PHP and MySQL if that helps to narrow your focus.

    Read the article

  • A good data model for finding a user's favorite stories

    - by wings
    Original Design Here's how I originally had my Models set up: class UserData(db.Model): user = db.UserProperty() favorites = db.ListProperty(db.Key) # list of story keys # ... class Story(db.Model): title = db.StringProperty() # ... On every page that displayed a story I would query UserData for the current user: user_data = UserData.all().filter('user =' users.get_current_user()).get() story_is_favorited = (story in user_data.favorites) New Design After watching this talk: Google I/O 2009 - Scalable, Complex Apps on App Engine, I wondered if I could set things up more efficiently. class FavoriteIndex(db.Model): favorited_by = db.StringListProperty() The Story Model is the same, but I got rid of the UserData Model. Each instance of the new FavoriteIndex Model has a Story instance as a parent. And each FavoriteIndex stores a list of user id's in it's favorited_by property. If I want to find all of the stories that have been favorited by a certain user: index_keys = FavoriteIndex.all(keys_only=True).filter('favorited_by =', users.get_current_user().user_id()) story_keys = [k.parent() for k in index_keys] stories = db.get(story_keys) This approach avoids the serialization/deserialization that's otherwise associated with the ListProperty. Efficiency vs Simplicity I'm not sure how efficient the new design is, especially after a user decides to favorite 300 stories, but here's why I like it: A favorited story is associated with a user, not with her user data On a page where I display a story, it's pretty easy to ask the story if it's been favorited (without calling up a separate entity filled with user data). fav_index = FavoriteIndex.all().ancestor(story).get() fav_of_current_user = users.get_current_user().user_id() in fav_index.favorited_by It's also easy to get a list of all the users who have favorited a story (using the method in #2) Is there an easier way? Please help. How is this kind of thing normally done?

    Read the article

< Previous Page | 30 31 32 33 34 35 36 37 38 39 40 41  | Next Page >