Search Results

Search found 4129 results on 166 pages for 'models'.

Page 5/166 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Rails Multiple Models per Form, Optional FK Association

    - by ckarbass
    Given the following pseudo-code: Company has_many :jobs Job belongs_to :company I'm creating a form to post a new job. In the form, I want to have two fields for an optional company. On submission, if a company was entered, I want to either create or update the company and associate it with the new job. I know if the company exists by searching the companies table for the company's url. Is it possible to do this using form_for, fields_for, and accepts_nested_attributes_for given the company may not exist?

    Read the article

  • Complex derived attributes in Django models

    - by rabidpebble
    What I want to do is implement submission scoring for a site with users voting on the content, much like in e.g. reddit (see the 'hot' function in http://code.reddit.com/browser/sql/functions.sql). My submission model currently keeps track of up and down vote totals. Currently, when a user votes I create and save a related Vote object and then use F() expressions to update the Submission object's voting totals. The problem is that I want to update the score for the submission at the same time, but F() expressions are limited to only simple operations (it's missing support for log(), date_part(), sign() etc.) From my limited experience with Django I can see 4 options here: extend F() somehow (haven't looked at the code yet) to support the missing SQL functions; this is my preferred option and seems to fit within the Django framework the best define a scoring function (much like reddit's 'hot' function) in my database, and have Django use the value of that function for the value of the score field; as far as I can tell, #2 is not possible wrap my two step voting process in a suitably isolated transaction so that I can calculate the voting totals in Python and then update the Submission's voting totals without fear that another vote against the submission could be added/changed in the meantime; I'm hesitant to take this route because it seems overly complex - what is a "suitably isolated transaction" in this case anyway? use raw SQL; I would prefer to avoid this entirely -- what's the point of an ORM if I have to revert to SQL for such a common use case as this! (Note that this coming from somebody who loves sprocs, but is using Django for ease of development.) Before I embark on this mission to extend F() (which I'm not sure is even possible), am I about to reinvent the wheel? Is there a more standard way to do this? It seems like such a common use case and yet in an hour of searching I have yet to find a common solution...

    Read the article

  • Using Markov models to convert all caps to mixed case and related problems

    - by hippietrail
    I've been thinking about using Markov techniques to restore missing information to natural language text. Restore mixed case to text in all caps Restore accents / diacritics to languages which should have them but have been converted to plain ASCII Convert rough phonetic transcriptions back into native alphabets That seems to be in order of least difficult to most difficult. Basically the problem is resolving ambiguities based on context. I can use Wiktionary as a dictionary and Wikipedia as a corpus using n-grams and Markov chains to resolve the ambiguities. Am I on the right track? Are there already some services, libraries, or tools for this sort of thing? Examples GEORGE LOST HIS SIM CARD IN THE BUSH - George lost his SIM card in the bush tantot il rit a gorge deployee - tantôt il rit à gorge déployée

    Read the article

  • Aggregation over a few models - Django

    - by RadiantHex
    Hi folks, I'm trying to compute the average of a field over various subsets of a queryset. Player.objects.order_by('-score').filter(sex='male').aggregate(Avg('level')) This works perfectly! But... if I try to compute it for the top 50 players it does not work. Player.objects.order_by('-score').filter(sex='male')[:50].aggregate(Avg('level')) This last one returns the exact same result as the query above it, which is wrong. What am I doing wrong? Help would be very much appreciated!

    Read the article

  • Why repeat database constraints in models?

    - by BWelfel
    In a CakePHP application, for unique constraints that are accounted for in the database, what is the benefit of having the same validation checks in the model? I understand the benefit of having JS validation, but I believe this model validation makes an extra trip to the DB. I am 100% sure that certain validations are made in the DB so the model validation would simply be redundant. The only benefit I see is the app recognizing the mistake and adjusting the view for the user accordingly (repopulating the fields and showing error message on the appropriate field; bettering the ux) but this could be achieved if there was a constraint naming convention and so the app could understand what the problem was with the save (existing method to do this now?)

    Read the article

  • Trying to make models in Kohana, relations problem.

    - by Asaf
    I have a table of Hits, Articles and Categories Now, a Hit belongs_to an Article/Category (depends on where it was done). so I have a column on Hits table with the name 'parenttype' That tells me 'Article' or 'Category'. I wrote in the Hit model (extends ORM) protected $_belongs_to= array( 'page' => array('model'=> $this->parenttype) ); Now it complains about $this-parenttype not being expected?

    Read the article

  • Django: CharField with fixed length, how?

    - by Giovanni Di Milia
    Hi everybody, I wold like to have in my model a CharField with fixed length. In other words I want that only a specified length is valid. I tried to do something like volumenumber = models.CharField('Volume Number', max_length=4, min_length=4) but it gives me an error (it seems that I can use both max_length and min_length at the same time). Is there another quick way? Thanks EDIT: Following the suggestions of some people I will be a bit more specific: My model is this: class Volume(models.Model): vid = models.AutoField(primary_key=True) jid = models.ForeignKey(Journals, db_column='jid', null=True, verbose_name = "Journal") volumenumber = models.CharField('Volume Number') date_publication = models.CharField('Date of Publication', max_length=6, blank=True) class Meta: db_table = u'volume' verbose_name = "Volume" ordering = ['jid', 'volumenumber'] unique_together = ('jid', 'volumenumber') def __unicode__(self): return (str(self.jid) + ' - ' + str(self.volumenumber)) What I want is that the volumenumber must be exactly 4 characters. I.E. if someone insert '4b' django gives an error because it expects a string of 4 characters. So I tried with volumenumber = models.CharField('Volume Number', max_length=4, min_length=4) but it gives me this error: Validating models... Unhandled exception in thread started by <function inner_run at 0x70feb0> Traceback (most recent call last): File "/Library/Python/2.5/site-packages/django/core/management/commands/runserver.py", line 48, in inner_run self.validate(display_num_errors=True) File "/Library/Python/2.5/site-packages/django/core/management/base.py", line 249, in validate num_errors = get_validation_errors(s, app) File "/Library/Python/2.5/site-packages/django/core/management/validation.py", line 28, in get_validation_errors for (app_name, error) in get_app_errors().items(): File "/Library/Python/2.5/site-packages/django/db/models/loading.py", line 131, in get_app_errors self._populate() File "/Library/Python/2.5/site-packages/django/db/models/loading.py", line 58, in _populate self.load_app(app_name, True) File "/Library/Python/2.5/site-packages/django/db/models/loading.py", line 74, in load_app models = import_module('.models', app_name) File "/Library/Python/2.5/site-packages/django/utils/importlib.py", line 35, in import_module __import__(name) File "/Users/Giovanni/src/djangoTestSite/../djangoTestSite/journaldb/models.py", line 120, in <module> class Volume(models.Model): File "/Users/Giovanni/src/djangoTestSite/../djangoTestSite/journaldb/models.py", line 123, in Volume volumenumber = models.CharField('Volume Number', max_length=4, min_length=4) TypeError: __init__() got an unexpected keyword argument 'min_length' That obviously doesn't appear if I use only "max_length" OR "min_length". I read the documentation on the django web site and it seems that I'm right (I cannot use both together) so I'm asking if there is another way to solve the problem. Thanks again

    Read the article

  • Django models & Python class attributes

    - by Geo
    The tutorial on the django website shows this code for the models: from django.db import models class Poll(models.Model): question = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') class Choice(models.Model): poll = models.ForeignKey(Poll) choice = models.CharField(max_length=200) votes = models.IntegerField() Now, each of those attribute, is a class attribute, right? So, the same attribute should be shared by all instances of the class. A bit later, they present this code: class Poll(models.Model): # ... def __unicode__(self): return self.question class Choice(models.Model): # ... def __unicode__(self): return self.choice How did they turn from class attributes into instance attributes? Did I get class attributes wrong?

    Read the article

  • Suggestions for a django db structure

    - by rh0dium
    Hi Say I have the unknown number of questions. For example: Is the sky blue [y/n] What date were your born on [date] What is pi [3.14] What is a large integ [100] Now each of these questions poses a different but very type specific answer (boolean, date, float, int). Natively django can happily deal with these in a model. class SkyModel(models.Model): question = models.CharField("Is the sky blue") answer = models.BooleanField(default=False) class BirthModel(models.Model): question = models.CharField("What date were your born on") answer = models.DateTimeField(default=today) class PiModel(models.Model) question = models.CharField("What is pi") answer = models.FloatField() But this has the obvious problem in that each question has a specific model - so if we need to add a question later I have to change the database. Yuck. So now I want to get fancy - How do a set up a model where by the answer type conversion happens automagically? ANSWER_TYPES = ( ('boolean', 'boolean'), ('date', 'date'), ('float', 'float'), ('int', 'int'), ('char', 'char'), ) class Questions(models.model): question = models.CharField(() answer = models.CharField() answer_type = models.CharField(choices = ANSWER_TYPES) default = models.CharField() So in theory this would do the following: When I build up my views I look at the type of answer and ensure that I only put in that value. But when I want to pull that answer back out it will return the data in the format specified by the answer_type. Example 3.14 comes back out as a float not as a str. How can I perform this sort of automagic transformation? Or can someone suggest a better way to do this? Thanks much!!

    Read the article

  • How can I iterate through all of the Models in my rails app?

    - by James
    I would like to be able to iterate over and inspect all the models in my rails app. In pseudo-code it would look something like: rails_env.models.each do |model| associations = model.reflect_on_all_associations(:has_many) ... do some stuff end My question is how do I inspect my rails app to get a collection of the models (rails_env.models) ?

    Read the article

  • Django admin site populated combo box based on imput

    - by user292652
    hi i have to following model class Match(models.Model): Team_one = models.ForeignKey('Team', related_name='Team_one') Team_two = models.ForeignKey('Team', related_name='Team_two') Stadium = models.CharField(max_length=255, blank=True) Start_time = models.DateTimeField(auto_now_add=False, auto_now=False, blank=True, null=True) Rafree = models.CharField(max_length=255, blank=True) Judge = models.CharField(max_length=255, blank=True) Winner = models.ForeignKey('Team', related_name='winner', blank=True) updated = models.DateTimeField('update date', auto_now=True ) created = models.DateTimeField('creation date', auto_now_add=True ) def save(self, force_insert=False, force_update=False): pass @models.permalink def get_absolute_url(self): return ('view_or_url_name') class MatchAdmin(admin.ModelAdmin): list_display = ('Team_one','Team_two', 'Winner') search_fields = ['Team_one','Team_tow'] admin.site.register(Match, MatchAdmin) i was wondering is their a way to populated the winner combo box once the team one and team two is selected in admin site ?

    Read the article

  • Django admin site auto populate combo box based on input

    - by user292652
    hi i have to following model class Match(models.Model): Team_one = models.ForeignKey('Team', related_name='Team_one') Team_two = models.ForeignKey('Team', related_name='Team_two') Stadium = models.CharField(max_length=255, blank=True) Start_time = models.DateTimeField(auto_now_add=False, auto_now=False, blank=True, null=True) Rafree = models.CharField(max_length=255, blank=True) Judge = models.CharField(max_length=255, blank=True) Winner = models.ForeignKey('Team', related_name='winner', blank=True) updated = models.DateTimeField('update date', auto_now=True ) created = models.DateTimeField('creation date', auto_now_add=True ) def save(self, force_insert=False, force_update=False): pass @models.permalink def get_absolute_url(self): return ('view_or_url_name') class MatchAdmin(admin.ModelAdmin): list_display = ('Team_one','Team_two', 'Winner') search_fields = ['Team_one','Team_tow'] admin.site.register(Match, MatchAdmin) i was wondering is their a way to populated the winner combo box once the team one and team two is selected in admin site ?

    Read the article

  • Django model manager didn't work with related object when I do aggregated query

    - by Satoru.Logic
    Hi, all. I'm having trouble doing an aggregation query on a many-to-many related field. Let's begin with my models: class SortedTagManager(models.Manager): use_for_related_fields = True def get_query_set(self): orig_query_set = super(SortedTagManager, self).get_query_set() # FIXME `used` is wrongly counted return orig_query_set.distinct().annotate( used=models.Count('users')).order_by('-used') class Tag(models.Model): content = models.CharField(max_length=32, unique=True) creator = models.ForeignKey(User, related_name='tags_i_created') users = models.ManyToManyField(User, through='TaggedNote', related_name='tags_i_used') objects_sorted_by_used = SortedTagManager() class TaggedNote(models.Model): """Association table of both (Tag , Note) and (Tag, User)""" note = models.ForeignKey(Note) # Note is what's tagged in my app tag = models.ForeignKey(Tag) tagged_by = models.ForeignKey(User) class Meta: unique_together = (('note', 'tag'),) However, the value of the aggregated field used is only correct when the model is queried directly: for t in Tag.objects.all(): print t.used # this works correctly for t in user.tags_i_used.all(): print t.used #prints n^2 when it should give n Would you please tell me what's wrong with it? Thanks in advance.

    Read the article

  • Post and Comment with the same Model.

    - by xRobot
    I have created a simple project where everyone can create one or more Blog. I want to use this models for Post and for Comment: class Post_comment(models.Model): content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField(_('object ID')) content_object = generic.GenericForeignKey() # Hierarchy Field parent = models.ForeignKey('self', null=True, blank=True, default=None, related_name='children') # User Field user = models.ForeignKey(User) # Date Fields date_submitted = models.DateTimeField(_('date/time submitted'), default = datetime.now) date_modified = models.DateTimeField(_('date/time modified'), default = datetime.now) title = models.CharField(_('title'), max_length=60, blank=True, null=True) post_comment = models.TextField(_('post_comment')) markup = models.IntegerField(choices=MARKUP_CHOICES, default=DEFAULT_MARKUP, null=True, blank=True) if it is a comment the parent is not null. So in most case the text field will contain a little bit of text. Can I use this model for both Post and Comment ?

    Read the article

  • ** EDITED ** 'NoneType' object has no attribute 'day'

    - by Asinox
    Hi guy, i dont know where is my error, but Django 1.2.1 is give this error: 'NoneType' object has no attribute 'day' when i try to save form from the Administrator Area models.py from django.db import models from django.contrib.auth.models import User class Editorial(models.Model): titulo = models.CharField(max_length=250,help_text='Titulo del editorial') editorial = models.TextField(help_text='Editorial') slug = models.SlugField(unique_for_date='pub_date') autor = models.ForeignKey(User) pub_date = models.DateTimeField(auto_now_add=True) activa = models.BooleanField(verbose_name="Activa") enable_comments = models.BooleanField(verbose_name="Aceptar Comentarios",default=False) editorial_html = models.TextField(editable=False,blank=True) def __unicode__(self): return unicode(self.titulo) def get_absolute_url(self): return "/editorial/%s/%s/" % (self.pub_date.strftime("%Y/%b/%d").lower(), self.slug) class Meta: ordering=['-pub_date'] verbose_name_plural ='Editoriales' def save(self,force_insert=False, force_update=False): from markdown import markdown if self.editorial: self.editorial_html = markdown(self.editorial) super(Editorial,self).save(force_insert,force_update) i dont know why this error, COMPLETED ERROR: Traceback: File "C:\wamp\bin\Python26\lib\site-packages\django\core\handlers\base.py" in get_response 100. response = callback(request, *callback_args, **callback_kwargs) File "C:\wamp\bin\Python26\lib\site-packages\django\contrib\admin\options.py" in wrapper 239. return self.admin_site.admin_view(view)(*args, **kwargs) File "C:\wamp\bin\Python26\lib\site-packages\django\utils\decorators.py" in _wrapped_view 76. response = view_func(request, *args, **kwargs) File "C:\wamp\bin\Python26\lib\site-packages\django\views\decorators\cache.py" in _wrapped_view_func 69. response = view_func(request, *args, **kwargs) File "C:\wamp\bin\Python26\lib\site-packages\django\contrib\admin\sites.py" in inner 190. return view(request, *args, **kwargs) File "C:\wamp\bin\Python26\lib\site-packages\django\utils\decorators.py" in _wrapper 21. return decorator(bound_func)(*args, **kwargs) File "C:\wamp\bin\Python26\lib\site-packages\django\utils\decorators.py" in _wrapped_view 76. response = view_func(request, *args, **kwargs) File "C:\wamp\bin\Python26\lib\site-packages\django\utils\decorators.py" in bound_func 17. return func(self, *args2, **kwargs2) File "C:\wamp\bin\Python26\lib\site-packages\django\db\transaction.py" in _commit_on_success 299. res = func(*args, **kw) File "C:\wamp\bin\Python26\lib\site-packages\django\contrib\admin\options.py" in add_view 777. if form.is_valid(): File "C:\wamp\bin\Python26\lib\site-packages\django\forms\forms.py" in is_valid 121. return self.is_bound and not bool(self.errors) File "C:\wamp\bin\Python26\lib\site-packages\django\forms\forms.py" in _get_errors 112. self.full_clean() File "C:\wamp\bin\Python26\lib\site-packages\django\forms\forms.py" in full_clean 269. self._post_clean() File "C:\wamp\bin\Python26\lib\site-packages\django\forms\models.py" in _post_clean 345. self.validate_unique() File "C:\wamp\bin\Python26\lib\site-packages\django\forms\models.py" in validate_unique 354. self.instance.validate_unique(exclude=exclude) File "C:\wamp\bin\Python26\lib\site-packages\django\db\models\base.py" in validate_unique 695. date_errors = self._perform_date_checks(date_checks) File "C:\wamp\bin\Python26\lib\site-packages\django\db\models\base.py" in _perform_date_checks 802. lookup_kwargs['%s__day' % unique_for] = date.day Exception Type: AttributeError at /admin/editoriales/editorial/add/ Exception Value: 'NoneType' object has no attribute 'day' thanks guys sorry with my English

    Read the article

  • How to make custom join query with Django ?

    - by xRobot
    I have these 2 models: genre = ( ('D', 'Dramatic'), ('T', 'Thriller'), ('L', 'Love'), ) class Book(models.Model): title = models.CharField(max_length=100) genre = models.CharField(max_length=1, choices=genre) class Author(models.Model): user = models.ForeignKey(User, unique=True) born = models.DateTimeField('born') book = models.ForeignKey(Book) I need to retrieve first_name and last_name of all authors of dramatic's books. How can I do this in django ?

    Read the article

  • Storing GenericForeignKey content_type in another model?

    - by slypete
    I have a typical definition/instance situation in my data modeling. I'm trying to store the content_type of a GenericForeignKey in another model (the definition model) like so: class IndicatorFieldInstance(models.Model): definition = models.ForeignKey(IndicatorField) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey(definition.content_type, 'object_id') indicator_instance = models.ForeignKey(IndicatorInstance) I've also tried it like this: content_object = generic.GenericForeignKey('definition__content_type', 'object_id') Neither of these methods seem to work. Is it possible to achieve this? For reference, here's the definition model: class IndicatorField(models.Model): name = models.CharField(max_length='255') content_type = models.ForeignKey(ContentType) indicator = models.ForeignKey(Indicator) Thanks, Pete

    Read the article

  • How do I relate two models/tables in Django based on non primary non unique keys?

    - by wizard
    I've got two tables that I need to relate on a single field po_num. The data is imported from another source so while I have a little bit of control over what the tables look like but I can't change them too much. What I want to do is relate these two models so I can look up one from the other based on the po_num fields. What I really need to do is join the two tables so I can do a where on a count of the related table. I would like to do filter for all Order objects that have 0 related EDI856 objects. I tried adding a foreign key to the Order model and specified the db_column and to_fields as po_num but django didn't like that the fact that Edi856.po_num wasn't unique. Here are the important fields of my current models that let me display but not filter for the data that I want. class Edi856(models.Model): po_num = models.CharField(max_length=90, db_index=True ) class Order(models.Model): po_num = models.CharField(max_length=90, db_index=True) def in_edi(self): '''Has the edi been processed?''' return Edi856.objects.filter(po_num = self.po_num).count() Thanks for taking the time to read about my problem. I'm not sure what to do from here.

    Read the article

  • Deploying Data Mining Models using Model Export and Import, Part 2

    - by [email protected]
    In my last post, Deploying Data Mining Models using Model Export and Import, we explored using DBMS_DATA_MINING.EXPORT_MODEL and DBMS_DATA_MINING.IMPORT_MODEL to enable moving a model from one system to another. In this post, we'll look at two distributed scenarios that make use of this capability and a tip for easily moving models from one machine to another using only Oracle Database, not an external file transport mechanism, such as FTP. The first scenario, consider a company with geographically distributed business units, each collecting and managing their data locally for the products they sell. Each business unit has in-house data analysts that build models to predict which products to recommend to customers in their space. A central telemarketing business unit also uses these models to score new customers locally using data collected over the phone. Since the models recommend different products, each customer is scored using each model. This is depicted in Figure 1.Figure 1: Target instance importing multiple remote models for local scoring In the second scenario, consider multiple hospitals that collect data on patients with certain types of cancer. The data collection is standardized, so each hospital collects the same patient demographic and other health / tumor data, along with the clinical diagnosis. Instead of each hospital building it's own models, the data is pooled at a central data analysis lab where a predictive model is built. Once completed, the model is distributed to hospitals, clinics, and doctor offices who can score patient data locally.Figure 2: Multiple target instances importing the same model from a source instance for local scoring Since this blog focuses on model export and import, we'll only discuss what is necessary to move a model from one database to another. Here, we use the package DBMS_FILE_TRANSFER, which can move files between Oracle databases. The script is fairly straightforward, but requires setting up a database link and directory objects. We saw how to create directory objects in the previous post. To create a database link to the source database from the target, we can use, for example: create database link SOURCE1_LINK connect to <schema> identified by <password> using 'SOURCE1'; Note that 'SOURCE1' refers to the service name of the remote database entry in your tnsnames.ora file. From SQL*Plus, first connect to the remote database and export the model. Note that the model_file_name does not include the .dmp extension. This is because export_model appends "01" to this name.  Next, connect to the local database and invoke DBMS_FILE_TRANSFER.GET_FILE and import the model. Note that "01" is eliminated in the target system file name.  connect <source_schema>/<password>@SOURCE1_LINK; BEGIN  DBMS_DATA_MINING.EXPORT_MODEL ('EXPORT_FILE_NAME' || '.dmp',                                 'MY_SOURCE_DIR_OBJECT',                                 'name =''MY_MINING_MODEL'''); END; connect <target_schema>/<password>; BEGIN  DBMS_FILE_TRANSFER.GET_FILE ('MY_SOURCE_DIR_OBJECT',                               'EXPORT_FILE_NAME' || '01.dmp',                               'SOURCE1_LINK',                               'MY_TARGET_DIR_OBJECT',                               'EXPORT_FILE_NAME' || '.dmp' );  DBMS_DATA_MINING.IMPORT_MODEL ('EXPORT_FILE_NAME' || '.dmp',                                 'MY_TARGET_DIR_OBJECT'); END; To clean up afterward, you may want to drop the exported .dmp file at the source and the transferred file at the target. For example, utl_file.fremove('&directory_name', '&model_file_name' || '.dmp');

    Read the article

  • Django syncdb not making tables for my app

    - by Rosarch
    It used to work, and now it doesn't. python manage.py syncdb no longer makes tables for my app. From settings.py: INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'mysite.myapp', 'django.contrib.admin', ) What could I be doing wrong? The break appeared to coincide with editing this model in models.py, but that could be total coincidence. I commented out the lines I changed, and it still doesn't work. class MyUser(models.Model): user = models.ForeignKey(User, unique=True) takingReqSets = models.ManyToManyField(RequirementSet, blank=True) takingTerms = models.ManyToManyField(Term, blank=True) takingCourses = models.ManyToManyField(Course, through=TakingCourse, blank=True) school = models.ForeignKey(School) # minCreditsPerTerm = models.IntegerField(blank=True) # maxCreditsPerTerm = models.IntegerField(blank=True) # optimalCreditsPerTerm = models.IntegerField(blank=True) UPDATE: When I run python manage.py loadddata initial_data, it gives an error: DeserializationError: Invalid model identifier: myapp.SomeModel Loading this data had worked fine before. This error is thrown on the very first data object in the data file.

    Read the article

  • Django says the "id may not be NULL" but why is it?

    - by Oli
    I'm going crazy today. I just tried to insert a new record and it threw back a "post_blogpost.id may not be NULL" error. Here's my model: class BlogPost(models.Model): title = models.CharField(max_length=100) slug = models.SlugField(max_length=100) who = models.ForeignKey(User, default=1) when = models.DateTimeField() intro = models.TextField(blank=True, null=True) content = models.TextField(blank=True, null=True) counter = models.PositiveIntegerField(default=0) published = models.BooleanField(default=False) css = models.TextField(blank=True, null=True) class Meta: ordering = ('-when', 'id') There are a number of functions beneath the model too but I won't include them in full here. Their names are: content_cache_key, clear_cache, __unicode__, reads, read, processed_content. I'm adding through the admin... And I'm running out of hair.

    Read the article

  • Getting the last member of a group on an intermediary M2M

    - by rh0dium
    If we look at the existing docs, what is the best way to get the last member added? This is similar to this but what I want to do is to be able to do this. group = Group.objects.get(id=1) group.get_last_member_added() #This is by ('-date_added') <Person: FOO> I think the best way is through a manager but how do you do this on an intermediary model? class Person(models.Model): name = models.CharField(max_length=128) def __unicode__(self): return self.name class Group(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField(Person, through='Membership') def __unicode__(self): return self.name class Membership(models.Model): person = models.ForeignKey(Person) group = models.ForeignKey(Group) date_joined = models.DateField() invite_reason = models.CharField(max_length=64)

    Read the article

  • Foreign Key Relationships

    - by Yehonathan Quartey
    I have two models class Subject(models.Model): name = models.CharField(max_length=100,choices=COURSE_CHOICES) created = models.DateTimeField('created', auto_now_add=True) modified = models.DateTimeField('modified', auto_now=True) syllabus = models.FileField(upload_to='syllabus') def __unicode__(self): return self.name and class Pastquestion(models.Model): subject=models.ForeignKey(Subject) year =models.PositiveIntegerField() questions = models.FileField(upload_to='pastquestions') def __unicode__(self): return str(self.year) Each Subject can have one or more past questions but a past question can have only one subject. I want to get a subject, and get its related past questions of a particular year. I was thinking of fetching a subject and getting its related past question. Currently am implementing my code such that I rather get the past question whose subject and year correspond to any specified subject like this_subject=Subject.objects.get(name=the_subject) thepastQ=Pastquestion.objects.get(year=2000,subject=this_subject) I was thinking there is a better way to do this. Or is this already a better way? Please Do tell ?

    Read the article

  • Value [...] not a valid choice, django-updown

    - by tamara
    I am trying to implemet django-updown https://github.com/weluse/django-updown. When I try to add vote trough the admin panel it says Value 1 not a valid choice. This is the models.py from the application: _SCORE_TYPE_CHOICES = ( ('-1', 'DISLIKE'), ('1', 'LIKE'), ) SCORE_TYPES = dict((value, key) for key, value in _SCORE_TYPE_CHOICES) class Vote(models.Model): content_type = models.ForeignKey(ContentType, related_name="updown_votes") object_id = models.PositiveIntegerField() key = models.CharField(max_length=32) score = models.SmallIntegerField(choices=_SCORE_TYPE_CHOICES) user = models.ForeignKey(User, blank=True, null=True, related_name="updown_votes") ip_address = models.IPAddressField() date_added = models.DateTimeField(default=datetime.datetime.now, editable=False) date_changed = models.DateTimeField(default=datetime.datetime.now, editable=False) Do you have an idea what could be wrong?

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >