Menu
  • HOME
  • TAGS

Model.objects.get returns nothing

python,django,object,get,models

I solved it by using transaction.commit() before my second query.

Variable has different values inside and outside a function

javascript,function,models

This was going to be a comment but it is so huge, so take it as a comment: It is possible that the oModel.read function is asynchronous so when you execute the code basically that happen is this: 1) You declare the variable as 0. 2) You execute read function....

Rail3 to Rails 4; changing conditions to where

ruby-on-rails,ruby-on-rails-4,models

Change it to this: has_many :businesses, -> { where(business_admins: { state: 'accepted'}) }, through: :business_admins Also see the Rails documentation....

Phalcon - search with joins

php,search,orm,models,phalcon

You should use queryBuilder for best performance. Anyway if you alias your relation and stick to objects rather than arrays youre able to make some tricks like: // in users model $this->belongsTo( 'id', // local id 'Posts', // model relation 'user_id', [ // related id 'alias' => 'posts' // alias...

MVC 5 Multiple Models in a Single View

asp.net,forms,asp.net-mvc-5,models

I would say this is good example of using ViewModel here. I would suggest something like - Create ViewModel with the composition of the two classes public class AddWeightModel { [Required] [DataType(DataType.Text)] [Display(Name = "Stone")] public Nullable<short> Stone { get; set; } [Required] [DataType(DataType.Text)] [Display(Name = "Pound")] public Nullable<short> Pound...

Django: Creating editable default values for model instance based on foreignkey existance

python,django,database,models

If you want to set links/displays default value in DocLink instance based on trann field you can override model's save method. For example following code shows how to set t_link if it doesn't have a value: class DocLink(models.Model): trann = models.ForeignKey(Transaction) t_link = models.CharField(max_length=2000) t_display = models.CharField(max_length=1000) p_display = models.CharField(max_length=300)...

Review model - shared across two different other models

ruby-on-rails,associations,models

This is the use case that single table inheritance (STI) was designed for. When most of the values are shared between two models, STI can let you inherit both of them from another model. E.g.: class Review < ActiveRecord::Base; end class DishReview < Review belongs_to :dish end class OrderReview <...

laravel work safely with mass assignments

php,laravel,eloquent,models,laravel-5

What you can do is: $model_object = Model::fill(['other_attributes' => 'other_values']); $model_object->guarded_field = 'value'; $model_object->save(); EDIT There is one more thing. If when using store/update you handle attribute in the code, you can safely add it to fillable attributes (you don't need to use it in guarded. $input = $request->input(); $input['guarded_field']...

Android coustom Listview is not showing

android,listview,android-listview,models

Problem is getcount method it should be as below. @Override public int getCount () { return users.size(); } ...

Get the user name based on the id in Laravel

php,laravel-4,models,relationships

In the TypeCost model hasMany relationship returns an object of type Collection, you have 2 options, using first or tour the object using foreach, also in the User model the relationship belongsToMany returns an object of type Collection, here you can see an example: {{ $type_cost->user->first()->username }} or @foreach($type_cost->user as...

Why a virtual property getter should not be called in cakePHP 3?

cakephp,models,cakephp-3.0

The problem here seems to be name of the table class, respetively the name of the entity class, probably depends on your perspective. By default, the name of the corresponding entity class is guessed by using the singular table class name without the trailing Table, however Agpois doesn't inflect to...

How do I reference multiple models in flask?

flask,models

Yes, you can use multiple modules for your models. Nothing in Flask or Python limits you to a specific module name or to just one module. If you are using Flask-SQLAlchemy, just make sure you import the db object (the SQLAlchemy instance that defines the Model object) in each. When...

Django - Use class as inline in both parent and parent of parent

django,django-admin,inline,models

Django doesn't support this (yet) but django-nested-inline can do the job.

Does the varIdent function, used in LME work fine?

r,models

A common trap in lme is that the default is to give raw residuals, i.e. not adjusted for any of the heteroscedasticity (weights) or correlation (correlation) sub-models that may have been used. From ?residuals.lme: type: an optional character string specifying the type of residuals to be used. If ‘"response"’, as...

Should I avoid multi-table (concrete) inheritance in Django by any means?

django,inheritance,models,multi-table-inheritance,concrete-inheritance

First of all, inheritance has not a natural translation to relational database architecture (ok, I know, Oracle Type Objects and some other RDBMS support inheritance but django don't take advantage of this functionality ) At this point, notice than django generates new tables to subclasses and write lots of left...

How to use Unicode for a ForeignKeyField, Django

python,django,unicode,models

Try this: def __unicode__(self): return unicode(self.cliente) ...

Connecting two models belongs_to/has_many and selecting via dropdown in form

ruby-on-rails,key,models,rails-models

I tried above code and its working fine. I can save contact with group_id without any change in your code. Please check again. Are you getting group_id in params in controller?

How to change upload_to parameter of ImageField based on field name in Django?

django,models,filefield,imagefield

In the upload_to keyword you would need to provide a function that you will define, for instance: def path_file_name(instance, filename): return '/'.join(filter(None, (instance.info.mouja, instance.info.doc_type, filename))) class Image(models.Model): content = models.ImageField(upload_to=path_file_name) From Django documentation: Model field reference: This may also be a callable, such as a function, which will be called...

This should not be nil

ruby-on-rails,rspec,entity-relationship,relationship,models

@blog => #<Blog id: 26, title: "user_blog_26"> @blog has an id assigned to it. So, that means its an existing record in blogs table with id = 26. @user.blogs.create(title: @blog.title) This line means that create a new record in blogs table with title same as that of @blog.title (i.e., user_blog_26)...

Add HTML form values to models in Django

django,forms,models

You must use request.POST.get() for getting the attributes that are send by the url, and send to the f = User(request.POST)the attributes for the model like u = User(name=name, subject=subject) #views.py def add_user(request): if request.method == 'POST': name = request.POST.get('name', '') subject = request.POST.get('subject', '') u = User(name=name, subject=subject) u.save()...

Weird issue has_many through association in updated Rails

ruby-on-rails,ruby,ruby-on-rails-4,activerecord,models

FYI, I can confirm this is an issue with ActiveRecord and Ruby 2.2. I was using ActiveRecord 3.2 and since changing to the 3-2-stable branch, the issue is gone. I believe this is fixed now in 4.x branches. I have raised an issue for this at https://github.com/rails/rails/issues/18991.

Adding FieldFile objects without form in django

python,django,models

Try using a django file instead of just an open file. from django.core.files import File ... f = open(FILENAME,'r') A=XML() A.xml.save(filename, File(f), save=True) A.save() ...

Best way to store category and subcategories of an item in Django models

python,django,database,models

If you can reorganize your models, you can make use of models inheritance (https://docs.djangoproject.com/en/1.8/topics/db/models/#model-inheritance) Your Item model could have been a sub class of Shorten_Item, given that it only contains one extra field, the cl = CharField() You can keep Shorten_Item as it is, then make Item inherit from that...

Need help writing a method to calculate duration (time) for Model/Views?

ruby-on-rails,ruby,validation,methods,models

Here is the approach I would probably take: The comments to the right were added just to explain a little of what was going on. validate :duration private def duration length = (ends_at - starts_at) / 60 return if length.between?(30, 120) # bail out of validation if length falls between...

how to display articles by user in django?

django,user,views,models

Use a values() command in your queryset. user_articles = Article.objects.filter(whopost=request.user.userprofile.id).values('whopost').order_by('-pub_date') ...

How do I use findOrCreateEach in waterline/sailsjs?

sails.js,models,waterline

findOrCreateEach is deprecated; that's why it's not in the documentation. The best way to replicate the functionality is by using .findOrCreate() in an asynchronous loop, for example with async.map: // Example: find or create users with certain names var names = ["scott", "mike", "cody"]; async.map(names, function(name, cb) { // If...

NameError: name 'Usuario' is not defined

python,django,migration,models

Amigo class did not defined on moment of declaration of Usuario class, so you cant use it in amigos field. From django docs: If you need to create a relationship on a model that has not yet been defined, you can use the name of the model, rather than the...

Django - how to create duplicate apps without duplicating the code (models, signals and so on)

django,models

You should move all the identical code to the app_shared application and import it from app_company1 and app_company2. If have separate tables in the DB is a requirement, then the inventory and transaction models should be defined as abstract in app_shared. app_company1 and app_company2 should create their own corresponding models...

Error when creating database record on rails console

ruby-on-rails,ruby,console,models

It looks like you have not yet run rake db:create This will "create" the databases on your PostgreSQL server. A step that you didn't have to do with SQLite, but Postgres requires it. As TK-421 said, make sure that your database.yml is configured for your OS and Postgres, not SQLite....

Ember Model and Component, getting components to detect changes in models

javascript,ember.js,controller,components,models

Computed properties aren't evaluated unless they are used. They are lazily evaluated. Using either of those properties will cause them to be evaluated and your logs will occur. http://jsbin.com/suheroya/1/edit Additionally it's important to know that the model itself isn't changing, so that computed property won't be called over and over....

Codeigniter errors for model array

php,mysql,codeigniter,models,controllers

try $data['quote']= $this->quotes_model->get_records(); $this->load->view('welcome_message', $data); and return your result from model:- return $query->result(); or return $query; ...

Django Multiple Foreign Key Model

python,sql,django,foreign-keys,models

There are at least four approaches to the "both companies of type X and companies of type Y have contacts" problem: Two tables: Companies and Contacts. There is an enumerated property on Companies which has values X and Y, and every contact has one foreign key to a company. Three...

How to create an ember model from json file

json,ember.js,autocomplete,models

Not sure I completely understand the question, but you can load arbitrary payloads into the the data store by calling pushPayload var pushData = { autocompleteObjects: [ {id: 1, value1: "foo", value2: "bar"} ] } store.pushPayload('autocompleteObject', pushData) Maybe in your app you could get for the JSON file and push...

How to obtain different type of collections for the same Model in an Association in Rails 4?

ruby-on-rails,ruby,rails-activerecord,models,model-associations

Assuming your Job can only have one worker that is set when a Proposal is accepted, you'd want something like this: class Job < ActiveRecord::Base belongs_to :poster, class_name: 'User', foreign_key: 'poster_id' belongs_to :worker, class_name: 'User', foreign_key: 'worker_id' has_many :proposals, dependent: :destroy end class User < ActiveRecord::Base has_many :posted_jobs, class_name: 'Job',...

How do I use the value of an attribute within a model? Ruby on Rails

ruby-on-rails,validation,models

The easiest way will be to write a custom validation method, as described in the Active Record Validations Rails Guide. In your case, it might look something like this: class Degree < ActiveRecord::Base validate :validate_awarded_by_inclusion_dependent_on_degree_type # ... def validate_awarded_by_inclusion_dependent_on_degree_type valid_awarded_by_values = Degree.schools(degree_type) unless valid_awarded_by_values.include?(awarded_by) error_msg = "must be " <<...

How to build complex django query as a string

django,models,django-queryset

Construct a Q object and use it in filter(): from viewer.models import Model1 from django.db.models import Q list1 = [ {'nut' : 'peanut', 'jam' : 'blueberry'}, {'nut' : 'almond', 'jam' : 'strawberry'} ] q = Q() for x in list1: q.add(Q(**x), Q.OR) query_results = Model1.objects.filter(q) Or, you can use operator.or_...

Caching for model in rails

ruby-on-rails,caching,models

I guess you are looking for counter_cache The :counter_cache option can be used to make finding the number of belonging objects more efficient Consider these models: class Order < ActiveRecord::Base belongs_to :customer, counter_cache: true end class Customer < ActiveRecord::Base has_many :orders end With this declaration, Rails will keep the cache...

Ruby on Rails If a user has already added data for one product stop them from doing so again relationship

ruby-on-rails,ruby,relationship,models,belongs-to

I would do a model relation like this: user.rb has_many :reviews product.rb has_many :reviews reviews.rb belongs_to :user belongs_to :product # This does the magic for the multiple validation validates_uniqueness_of :user_id, :scope => :product_id, :message=>"You can't review a product more than once", on: 'create' As you can see, i will let...

Pattern to organize related items into groups

python,django,models

Do the grouping in the backend of the view instead of the template. In your view, create a dictionary like this: sorted_groceries = { store1 : [item1, item2], store2 : [item3, item4], } which can be done with some code resembling this pseudo-code: sorted_groceries = {} for item in shopping...

Java 3D LWJGL collision

java,lwjgl,models,collision,detection

You have a few options here. The easiest is to simply create an axis-aligned bounding box (AABB) around the object; this can be done algorithmically by simply finding the minimum and maximum values for each axis. For some applications this will work fine, but this obviously isn't very precise. It's...

Order parent model using children in rails

ruby-on-rails,order,models

@products = Product.order("count(votes) DESC") If you have not votes column then use: @products = Product.all.sort { |a, b| b.votes.count <=> a.votes.count } ...

What do navigation properties do in Entity Framework?

c#,entity-framework,models

2: if you do virtual navigation properties then will work lazy load value of this property: public class Book { //... public int AuthorId { get; set; } public virtual Author Author { get; set; } } It work: EF create proxy to your entity (Book) and overrides navigation property...

User history actions - The proper way to store in django models

django,django-models,models

you can get inspired from django's admin log from django.contrib.admin.models import LogEntry or use it if it matches your requirements. Checkout this

Extending a package model

php,laravel-4,models,extends,extending-classes

The easiest way is to fork the package on github, make the changes to the package yourself, then pull in your custom package on composer (instead of the original package). This way you maintain control over your changes on the other package. The specific method for pulling in your fork...

Rails not loading referencial attribute

mysql,ruby-on-rails,models,database-migration

When you use belongs_to in Rails, you're saying that the model containing the belongs_to has the foreign key to the other object. In this case, you've placed the foreign key, role_id on the User model. Therefore, the User model should contain the belongs_to :role, and the Role model should contain...

upload_to dynamically generated url to callable

python,django,models

It looks like (re-reading your post it's not 100% clear) what you want is a partial application. Good news, it's part of Python's stdlib: import os from functools import partial def generic_upload_to(instance, filename, folder): return os.path.join(instance.name, folder, filename) class Project(TimeStampedModel): name = models.TextField(max_length=100, default='no name') logo = models.ImageField( upload_to=partial(generic_upload_to, folder="logo")...

sails.js: Lifecycle callbacks for Models: Do they support beforeFind and afterFind?

sails.js,models,waterline

As of writing this it does NOT support these requests, however their is a pull request https://github.com/balderdashy/waterline/pull/525 You can use policies to do this in the mean time....

How can I save an empty model (I only need it's pk created)

python,django,models

"Storage" that holds 2 "StorageType" That means Storage can have many StorageType and StorageType can have Storages. Make a new ManyToMany Field in the storage. class Storage(models.Model): storage_types = models.ManyToManyField(StorageType) def __unicode__(self): return str(self.id) class StorageType(models.Model): tripa = 'Tripa' portada = 'Portada' type_choice = ( (tripa, 'Tripa'), (portada, 'Portada'),...

Rails: Select from multiple models

ruby-on-rails,ruby,ruby-on-rails-4,activerecord,models

I don't really understand the difference between Company and Organization. I'm assuming Company and Organization have no relation to each other. So you can just union the two sets. <% companies_and_organizations = (Company.all.pluck(:name) + Organization.all.pluck(:name)).sort %> <%= f.text_field :company_name, data: {autocomplete_source: companies_and_organizations}, required: true %> Then I assume you only...

rails rake creates no models

ruby-on-rails,rake,models,migrate

There is a typo here: it is db:migrate (instead of bd:migrate). Also, rake does not create models. To create models along with migrations, use rails generate model MyModel. On the other hand, if all your tables are created using migrations, then just create the model files manually in the app/models...

Django: many to many relationship model definition

python,django,database,models

You are looking for an Extra fields on many-to-many relationships Your code should look like this: class Bank(models.Model): name = models.Charfield() money = models.IntegerField() members = models.ManyToManyField(StockShares, through='Sale') class StockShares(models.Model): name = models.Charfield() price = models.Charfield() class Sale(models.Model): bank = models.ForeignKey(Bank) stockshares = models.ForeignKey(StockShares) date = models.DateField() Maybe quantity should...

ForeignKey from base class model to inheritor error

python,django,orm,models

There is no need to add the trc field, because it will already exist. Check out the very similar example in the django docs on multi-table inheritance: If you have a Place that is also a Restaurant, you can get from the Place object to the Restaurant object by using...

Problems forming multiple collections and models in Backbone.js

json,backbone.js,collections,models

Remove the id from the defaults altogether. The id is a representation of id's that are present in the back end; if the id on a Backbone model is present, then the library assumes that you are working with a model that exists in the back end (and has a...

Deciding how to model this data in django

django,models

class Language(models.Model): name = models.CharField(max_length=100) class Word(models.Model): name = models.CharField(max_length=100) language = models.ForeignKey(Language, related_name='language_words') #... class Translation(models.Model): word = models.ForeignKey(Word, related_name='word_translations') translation = models.CharField(max_length=100) from_language = models.ForeignKey(Language, related_name='language_translations') in_language = models.CharField(max_length=100) # stage performances english_language =...

Django 1.6: model fields not showing

python,django,django-views,models

You need to pass the list to template from the view. In your code, the variable doctor is not defined in the template, so it doesn't show anything. Change your view to pass doctlist as def allDocs(request): return render(request, 'meddy1/doclistings.html', {'doclist': Doctor.objects.all()}) Update template to use doclist to show each...

Using form_for with multiple models?

ruby-on-rails,forms,models

I think you are looking for rails built-in helper fields_for. See the docs here....

Rails 4 - Titleize on read, downcase on save, in model

ruby-on-rails,models

You could make a custom getter... class User < ActiveRecord::Base def username self[:username].titleize end end If you want it only on reads for views but not on reads for edits then you might be better off using a decorator. https://github.com/drapergem/draper...

Django creating model instances without keyword arguments

python,django,arguments,instance,models

Have you tried the following code: obj = SomeModel(None, "a_stuff", "b_stuff", "c_stuff", "d_stuff", "e_stuff", "f_stuff") obj.save() Hope these helps....

I've read not to nest resources more than 2. How should I nest my Hotel/Room/Visit Model?

ruby-on-rails,associations,models,nesting

Shallow Nesting "One way to avoid deep nesting (as recommended above) is to generate the collection actions scoped under the parent, so as to get a sense of the hierarchy, but to not nest the member actions." See Rails Guide on Routing Section 2.7.2 Shallow Nesting for more information In...

Strange has_many Association Behavior in Rails 4

ruby-on-rails,ruby,ruby-on-rails-4,models

So, I went and looked at code of mine that does a similar function. Here's what my create method looks like. This is creating a Student with assignment to Student Groups in a school setting (I didn't use "class" since Ruby wouldn't like that). def create @student = Student.new(student_params) if...

Web api: Retrieve m2m model vs Retrieve main model

design,views,models,m2m

I wouldn't complicate the matters on a frontend with a new model / api / controller (JobFavourite) in this particular case unless it is absolutely necessary. I would make "favourite" a filter on Job's controller. So, on a filtered job list view you call GET /jobs?favourites=true to get only favourited...

Rails validation / scope on 24 hour period

ruby-on-rails,validation,models

It might be easier to just make an explicit validator method for this: class Foo < ActiveRecord::Base validate :ip_address_uniqueness, on: :create # ... def ip_address_uniqueness existing = Foo.where(impressionable_id: self.impressionable_id) .where(ip_address: self.ip_address) .where(created_at: Time.current.all_day) errors.add(:ip_address, 'cannot be used again today') if existing end end ...

Getting error when trying to insert a record that has composite primary keys

php,sql,laravel,models

From what I can deduce, you have a Friendship Eloquent Model attached to the friendship pivot table. The problem with that is that Eloquent doesn't work with composite primary keys, so there's no real way of doing that. You should have a look at the Laravel Eloquent Docs to see...

rewriting unfilled field of the model in Django

python,django,models

YourModel.objects.filter(B='something').delete() or for empty foreign key: YourModel.objects.filter(B__isnull=True).delete() ...

How to get 'feed' method in User model not private so I can show feeds in my static_page/home page (Michael Hartl Rails Tutorial)

ruby-on-rails,ruby,activerecord,models

As per the error private methodfeed' called for #`, You are calling a private method named feed on an instance of Usermodel. In order to get the below code working @feed_items = current_user.feed.paginate(page: params[:page]) Make sure that method feed in User model is not under private section. Just remember, a...

Organize separate child Models under one namespace

ruby-on-rails,ruby,ruby-on-rails-4,widget,models

It's impossible to define this as an association. instead, you can define your own method: def widgets headers + galleries end but remember that the result of this method will be simple Array, not an ActiveRecord::Relation - so you won't be able to call AR scope methods on this. ...

invalid literal for int() with base 10 - django - updated

django,models,base,migrate

I solved this issue when deleting the old migrations files that django created.

Rails: Update loan amount with amount paid

ruby-on-rails,model-view-controller,models,controllers

You can just create a method in the Loan model make_payment(amount) and reduce the amount from the total loan amount. I would advice you to maintain a log of payments in order to keep track of them later. Create a Payment model that belongs to the Loan model....

Angular variables not updating outside loop

javascript,angularjs,loops,angularjs-scope,models

To start, you should move the implementation details outside of the view (i.e., you shouldn't be directly setting model.attack = power.attack in the view, that should be at least one level deeper, in the controller). With that, moving this to the controller will resolve your issue itself. Your view can...

How to separate the model into two applications

python,django,django-models,models

You can create two applications, one for Users and one for Countries. Then put the User model in the Users app and the Country model in the Countries app. Then in a third app you can import both as you need them: from countries.models import Country from users.models import User...

ForeignKey produces 'NoneType' object has no attribute '_meta' when doing a migrate

django,django-models,models

I've solved the issue importing the application module as it follows: from person import models as person_class And then, in the field of the OneToOneField: person = models.OneToOneField(person_class.Person, verbose_name=_(u"Person"), related_name="person") ...

Alternative for :id param

ruby-on-rails,ruby,models

In Your form You could use: <%= link_to @user.name, @user %> because You already wrote in UsersController: ... @user = User.find(custom_id: params[:id]) ... ...

Compare two lists of object for new, changed, updated on a specific property

c#,list,object,compare,models

Simple Linq New List<AccommodationImageModel> new = compareList.Where(c=>c.id==0).ToList(); To be deleted List<AccomodationImageModel> deleted = masterList.Where(c => !compareList.Any(d => d.id == c.id)).ToList(); To be updated List<AccomodationImageModel> toBeUpdated = masterList.Where(c => compareList.Any(d => c.id == d.id)).ToList(); ...

Efficient reverse of queryset

python,django,django-queryset,models

I may be wrong, but i feel like your model structure is not normalized. You have a M2M relation between Player and Item via Slots. Consider the following model structure: from django.db import models from django.contrib.auth.models import User class Slot(models.Model): #e.g. main_hand, off_hand, head, ... , feet name = models.CharField(max_length=255)...

Find if attribute of a model is 'required'

python,google-app-engine,models,app-engine-ndb

Although poorly documented, there is an introspection API for NDB models; simply use the name of the configuration option with an underscore prefixed: Contact._properties['name']._required is the value of the required option. The underscores do not signify 'privacy' here but are used to avoid clashing with names from the model itself...

Can not reach to associated models from Jquery

javascript,jquery,ruby-on-rails,controller,models

You are most likely trying to use javascript variable in ruby. This kind of confusion is one many reasons to avoid intermingling your client side and server side code. Instead you can use data attributes and ajax to pass data to javascript. <div id="map-canvas" data-initlat="<%= @initlat %>"></div> Or another example:...

Likelihood ratio test statsmodels

python,statistics,models,statsmodels

I don't see any problem. Generalized Linear Models are Maximum Likelihood models, if the scale is the one implied by the family. statsmodels.GLM doesn't currently implement Quasi-Likelihood methods where the scale can deviate from those of the underlying family, e.g. overdispersed Poisson, so the Likelihood Ratio test can be applied....

Best way of protecting the show() method against users accessing other users messages

laravel,laravel-4,routing,models,relationships

in the simplest form, in your MessagesController in the show method, you can add an additional parameter to your query and get the record where message_id = the paramater from the url and the user_id on that message is the authenticated user's ID.... do something like $message = App\Message::where('id', '=',...

Update and save records in a django.db.models.query.QuerySet object?

django,set,models

table.objects.all() is a django.query.QuerySet object. When you run x[0], you actually calls its __getitem__ method. You can find its implementation at github. Below is a simplified version. I only remove the safety check and slice code. def __getitem__(self, k): """ Retrieves an item or slice from the set of results....

Is there any java framework which allows developer to create models during runtime?

java,python,hibernate,models

If I understand well your question. You want to make some Java to SQL mapping which basicly do JPA(Hibernate) Hibernate is ORM tool "Object-relational mapping" Just check @Entity and you will find what you need eg. HERE....

get call stack for Model Classes in Django

python,django,django-models,models

If I understood you right, this is my solution. Any call to queryset api prints caller stack. import inspect from django.db import models from django.db.models import Manager class LogManager(Manager): def get_queryset(self): print inspect.stack() # in py3.4 the [2] element was the actual caller outside Manager so I used [2:] return...

Yii2 custom validator not working as guide suggests

validation,module,yii2,models,yii2-advanced-app

I guess this is what you want. First use the property "checked" in the whenClient of the input field to get if the checkbox is checked or not. The hidden field of the checkbox is not an issue. The whenClient in hero_linked (checkbox) is used to validate the hero_link (textinput)...

Need help on Django Modelling

python,django,models,modeling

You will need to validate the statuses count for each person in the clean method. from django.db import models from django.core.exceptions import ValidationError class Status(models.Model): name = models.CharField(max_length=30) class Person(models.Model): name = models.CharField(max_length=30) status = models.ManyToManyField(Status) def clean(self): # check person status count if self.status.all().count() > 3: raise ValidationError("Person can...

A query to search on the whole model [Laravel]

jquery,sql,laravel,models

Well you could add a where like for every column in the table: $columns = Schema::getColumnListing('users'); $query = User::query(); $search = Input::get('search'); foreach($columns as $column){ $query->orWhere($column, 'like', '%'.$search.'%'); } $users = $query->get(); ...

Yii sorting in model via certain values

php,sql-server,sorting,yii,models

to do such thing you need SQL statement like this. SELECT status FROM table_name ORDER BY CASE name WHEN 'New data' THEN 1 WHEN 'open data' THEN 2 WHEN 'pending data' THEN 3 END; in Yii model: $criteria = new CdbCriteria(); $criteria->order ="CASE Column_name WHEN 'New data' THEN 1 WHEN...

Self-referring to males in father field and females in mother field in model in rails?

ruby-on-rails,database,postgresql,models

On the Rails side, you could use a custom validator to ensure an Animal's father is a male (and mother a female). I don't know much about your specific models, but here's an example: class Animal < ActiveRecord::Base belongs_to :father, :class_name => "Animal" belongs_to :mother, :class_name => "Animal" validate :ensure_mother_and_father_are_correct_gender...

Rails modeling headache

ruby-on-rails,oop,models

It depends on whether you have many fields specific to agenda (not to month). If you do, it's better to have one separate model for agenda. BTW, It seems user and agenda are many-to-many relationship. In this case, you need one intermediate model between user and agenda. ...

Ruby on rails 'has many' relation error: undefined method

ruby-on-rails-4,associations,models

Please try like this: <% @artists = Artist.where(name: "Test").first %> <% @concertTest = @artists.concerts %> Note:- where will return Active record relation array....

Why is foreign_key ignored?

ruby-on-rails,ruby,associations,models

Shouldn't you be using belongs_to? class RealmType < ActiveRecord::Base has_many :realms, foreign_key: "realm_type_id" end class Realm < ActiveRecord::Base belongs_to :realm_type end ...

Symfony + Doctrine: Models and Inheritance

php,symfony2,doctrine2,models,entities

I've come up with a solution for this issue, and it does involve traits. What I'm doing is basically trying to create several variations of a table. The relationship between the reviews is more horizontal than vertical (One type of review might have ratings, another one a video, another both)....

EmberData manage model in controller without route

ember.js,controller,ember-data,models

To set properties on a controller not affiliated directly with a route by naming convention refer to the following jsbin. http://emberjs.jsbin.com/gugajaki/3/edit App = Ember.Application.create(); notifications = [ {seen: false, message: "tornado siren!!"} {seen: true, message: "Omg lol security breach"} {seen: false, message: "BFF Rite?"} {seen: false, message: "steve kane 4...

Entity type has no key defined EF6

entity-framework,asp.net-mvc-5,models

If you are using EF Code First (not specified in your question), you will need to change the ContactId property name to ContactsId to match the convention of ClassName + Id in order to define the key for your Contacts entity type. See the MSDN Code First Conventions: http://msdn.microsoft.com/en-us/data/jj679962.aspx...

How can I correctly setup models in Laravel 5 and fix my error?

php,laravel,model-view-controller,laravel-5,models

As you can see in the error, it tries to find the model in the same namespace as your controller: FatalErrorException in MyersController.php line 20: Class 'App\Http\Controllers\Myer' not found. In the Model, you can see it's in namespace App. So either put use App\Myer; in the top of your controller...