Search Results

Search found 448 results on 18 pages for 'foreignkey'.

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

  • django model relation definition

    - by Laurent Luce
    Hello, Let say I have 3 models: A, B and C with the following relations. A can have many B and many C. B can have many C Is the following correct: class A(models.Model): ... class B(models.Model): ... a = ForeignKey(A) class C(models.Model): ... a = ForeignKey(A) b = ForeignKey(B)

    Read the article

  • Is a many-to-many relationship with extra fields the right tool for my job?

    - by whichhand
    Previously had a go at asking a more specific version of this question, but had trouble articulating what my question was. On reflection that made me doubt if my chosen solution was correct for the problem, so this time I will explain the problem and ask if a) I am on the right track and b) if there is a way around my current brick wall. I am currently building a web interface to enable an existing database to be interrogated by (a small number of) users. Sticking with the analogy from the docs, I have models that look something like this: class Musician(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) dob = models.DateField() class Album(models.Model): artist = models.ForeignKey(Musician) name = models.CharField(max_length=100) class Instrument(models.Model): artist = models.ForeignKey(Musician) name = models.CharField(max_length=100) Where I have one central table (Musician) and several tables of associated data that are related by either ForeignKey or OneToOneFields. Users interact with the database by creating filtering criteria to select a subset of Musicians based on data the data on the main or related tables. Likewise, the users can then select what piece of data is used to rank results that are presented to them. The results are then viewed initially as a 2 dimensional table with a single row per Musician with selected data fields (or aggregates) in each column. To give you some idea of scale, the database has ~5,000 Musicians with around 20 fields of related data. Up to here is fine and I have a working implementation. However, it is important that I have the ability for a given user to upload there own annotation data sets (more than one) and then filter and order on these in the same way they can with the existing data. The way I had tried to do this was to add the models: class UserDataSets(models.Model): user = models.ForeignKey(User) name = models.CharField(max_length=100) description = models.CharField(max_length=64) results = models.ManyToManyField(Musician, through='UserData') class UserData(models.Model): artist = models.ForeignKey(Musician) dataset = models.ForeignKey(UserDataSets) score = models.IntegerField() class Meta: unique_together = (("artist", "dataset"),) I have a simple upload mechanism enabling users to upload a data set file that consists of 1 to 1 relationship between a Musician and their "score". Within a given user dataset each artist will be unique, but different datasets are independent from each other and will often contain entries for the same musician. This worked fine for displaying the data, starting from a given artist I can do something like this: artist = Musician.objects.get(pk=1) dataset = UserDataSets.objects.get(pk=5) print artist.userdata_set.get(dataset=dataset.pk) However, this approach fell over when I came to implement the filtering and ordering of query set of musicians based on the data contained in a single user data set. For example, I could easily order the query set based on all of the data in the UserData table like this: artists = Musician.objects.all().order_by(userdata__score) But that does not help me order by the results of a given single user dataset. Likewise I need to be able to filter the query set based on the "scores" from different user data sets (eg find all musicians with a score 5 in dataset1 and < 2 in dataset2). Is there a way of doing this, or am I going about the whole thing wrong?

    Read the article

  • How do I restrict foreign keys choices to related objects only in django

    - by Jeff Mc
    I have a two way foreign relation similar to the following class Parent(models.Model): name = models.CharField(max_length=255) favoritechild = models.ForeignKey("Child", blank=True, null=True) class Child(models.Model): name = models.CharField(max_length=255) myparent = models.ForeignKey(Parent) How do I restrict the choices for Parent.favoritechild to only children whose parent is itself? I tried class Parent(models.Model): name = models.CharField(max_length=255) favoritechild = models.ForeignKey("Child", blank=True, null=True, limit_choices_to = {"myparent": "self"}) but that causes the admin interface to not list any children.

    Read the article

  • Django form and User data

    - by Dean
    I have a model that looks like this: class Client(models.Model): name = models.CharField(max_length=100, primary_key=True) user = models.ForeignKey(User) class Contract(models.Model): title = models.CharField(max_length=100, primary_key=True) start_date = models.DateField() end_date = models.DateField() description = models.TextField() client = models.ForeignKey(Client) user = models.ForeignKey(User) How can i configure a django form so that only clients associated with that user show in the field in the form? My initial thought was this in my forms.py: client = forms.ModelChoiceField(queryset=Client.objects.filter(user__username = User.username)) But it didn't work. So how else would I go about it?

    Read the article

  • How to join the results of two tables in django python

    - by user1787524
    I have two models class Weather(model.model): region = models.ForeignKey(Region) district = models.ForeignKey(District) temp_max = models.IntegerField(blank=True, null=True, verbose_name='Max temperature (C)') temp_min = models.IntegerField(blank=True, null=True, verbose_name='Min temperature (C)') and class Plan(model.model): name = tinymce_models.HTMLField(blank=True, null=True) region = models.ForeignKey(Region) district = models.ForeignKey(District) Provided for every region and district have unique row. I want to combine the result so that i can get all the columns of both tables These two Models are not related to each other. ' I need to make the join like join weather w on w.region = A.region and w.distric = A.district so that result contains all the columns in everyobject like obj.temp_max etc

    Read the article

  • Parameterized Django models

    - by mgibsonbr
    In principle, a single Django application can be reused in two or more projects, providing functionality relevent to both. That implies that the same database structure (tables and relations) will be re-created identically in different databases, and most times this is not a problem (assuming the projects/databases are unrelated - for instance when someone downloads a complete app to use in their own projects). Sometimes, however, the models must be "tweaked" a little to better fit the problem needs. This can be accomplished by forking the app, but I wondered if there wouldn't be a better option in cases where the app designer can anticipate the most common customizations. For instance, if I have a model that could relate to another as one-to-one or one-to-many, I could specify the unique property as a parameter, that can be specified in the project's settings: class This(models.Model): other = models.ForeignKey(Other, unique=settings.OTHER_TO_THIS) Or if a model can relate to many others, I could create an intermediate table for each of them (thus enforcing referential integrity) instead of using generic fks: for related in settings.MODELS_RELATED_TO_OTHER: model_name = '%s_Other' % related globals()[model_name] = type(model_name, (models.Model,) { me:models.ForeignKey(find_model_class(related)), other:models.ForeignKey(Other), # Some other properties all intersection tables must have }) Etc. Let me stress out that I'm not proposing to change the models at runtime nor anything like that; once the parameters were defined and syncdb called for the first time, those parameters are not to be changed again (unless you're doing a schema migration). Is this a good design? Are there better ways to accomplish the same thing, or maybe drawbacks I coulnd't anticipate? This technique is meant to be used sparingly (only on apps meant to be reused in wildly different contexts, and only when a specific need of customization can be detected while the app model is being designed).

    Read the article

  • Django tests failing on invalid keyword argument

    - by Darwin Tech
    I have a models.py like so: from django.db import models from django.contrib.auth.models import User from datetime import datetime class UserProfile(models.Model): user = models.OneToOneField(User) def __unicode__(self): return self.user.username class Project(models.Model): user = models.ForeignKey(UserProfile) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) product = models.ForeignKey('tool.product') module = models.ForeignKey('tool.module') model = models.ForeignKey('tool.model') zipcode = models.IntegerField(max_length=5) def __unicode__(self): return unicode(self.id) And my tests.py: from django.test import TestCase, Client # --- import app models from django.contrib.auth.models import User from tool.models import Module, Model, Product from user_profile.models import Project, UserProfile # --- unit tests --- # class UserProjectTests(TestCase): fixtures = ['admin_user.json'] def setUp(self): self.product1 = Product.objects.create( name='bar', ) self.module1 = Module.objects.create( name='foo', enable=True ) self.model1 = Model.objects.create( module=self.module1, name='baz', enable=True ) self.user1 = User.objects.get(pk=1) ... def test_can_create_project(self): self.project1 = Model.objects.create( user=self.user1, product=self.product1, module=self.module1, model=self.model1, zipcode=90210 ) self.assertEquals(self.project1.zipcode, 90210) But I get a TypeError: 'product' is an invalid keyword argument for this function error. I'm not sure what is failing but I'm guessing something to do with the FK relationships... Any help would be much appreciated.

    Read the article

  • Replace textfields with dropdown select fields

    - by 47
    I have three model classes that look as below: class Model(models.Model): model = models.CharField(max_length=20, blank=False) manufacturer = models.ForeignKey(Manufacturer) date_added = models.DateField(default=datetime.today) def __unicode__(self): name = ''+str(self.manufacturer)+" "+str(self.model) return name class Series(models.Model): series = models.CharField(max_length=20, blank=True, null=True) model = models.ForeignKey(Model) date_added = models.DateField(default=datetime.today) def __unicode__(self): name = str(self.model)+" "+str(self.series) return name class Manufacturer(models.Model): MANUFACTURER_POPULARITY_CHOICES = ( ('1', 'Primary'), ('2', 'Secondary'), ('3', 'Tertiary'), ) manufacturer = models.CharField(max_length=15, blank=False) date_added = models.DateField(default=datetime.today) manufacturer_popularity = models.CharField(max_length=1, choices=MANUFACTURER_POPULARITY_CHOICES) def __unicode__(self): return self.manufacturer I want to have the fields for model series and manufacturer represented as dropdowns instead of text fields. I have customized the model forms as below: class SeriesForm(ModelForm): series = forms.ModelChoiceField(queryset=Series.objects.all()) class Meta: model = Series exclude = ('model', 'date_added',) class ModelForm(ModelForm): model = forms.ModelChoiceField(queryset=Model.objects.all()) class Meta: model = Model exclude = ('manufacturer', 'date_added',) class ManufacturerForm(ModelForm): manufacturer = forms.ModelChoiceField(queryset=Manufacturer.objects.all()) class Meta: model = Manufacturer exclude = ('date_added',) However, the dropdowns are populated with the unicode in the respective class...how can I further customize this to get the end result I want? Also, how can I populate the forms with the correct data for editing? Currently only SeriesForm is populated. The starting point of all this is from another class whose declaration is as below: class CommonVehicle(models.Model): year = models.ForeignKey(Year) series = models.ForeignKey(Series) .... def __unicode__(self): name = ''+str(self.year)+" "+str(self.series) return name

    Read the article

  • CakePHP - hasMany not fetching?

    - by Paolo Bergantino
    Maybe I am just having a slow day, but for the life of me I can't figure out why this is happening. I haven't done CakePHP in a while and I am trying to use the 1.3 version, but this doesn't seem to be working... I have two models: area.php <?php class Area extends AppModel { var $name = 'Area'; var $useTable = 'OR_AREA'; var $primaryKey = 'A_ID'; var $belongsTo = array( 'Building' => array( 'className' => 'Building', 'foreignKey' => 'FK_B_ID', ), 'Facility' => array( 'className' => 'Facility', 'foreignKey' => 'FK_F_ID', ), 'System' => array( 'className' => 'System', 'foreignKey' => 'FK_S_ID', ) ); } ?> building.php <?php class Building extends AppModel { var $name = 'Building'; var $useTable = 'OR_BLDG'; var $primaryKey = 'B_ID'; var $hasMany = array( 'Area' => array( 'className' => 'Area', 'foreignKey' => 'FK_B_ID', ) ); } ?> OR_AREA has a column titled FK_B_ID that refers to the B_ID. If I run something like: $this->Building->find('all', array('recursive' => 2)); I get empty [Area] arrays for all the Buildings even though there are plenty of Areas in the OR_AREA table that are associated to buildings. Not only that, the Query Table doesn't even show CakePHP attempted to find anything but all the records in OR_BLDG. All the more puzzling, if I do: $this->Area->find('all'); I get all the Areas and the [Building] arrays are populated when appropriate. What am I missing?

    Read the article

  • Working with extra fields in an Inline form - save_model, save_formset, can't make sense of the diff

    - by magicrebirth
    Suppose I am in the usual situation where there're extra fields in the many2many relationship: class Person(models.Model): name = models.CharField(max_length=128) class Group(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField(Person, through='Membership') class Membership(models.Model): person = models.ForeignKey(Person) group = models.ForeignKey(Group) date_joined = models.DateField() invite_reason = models.CharField(max_length=64) # other models which are unrelated to the ones above.. class Trip(models.Model): placeVisited = models.ForeignKey(Place) visitor = models.ForeignKey(Person) pleasuretrip = models.Boolean() class Place(models.Model): name = models.CharField(max_length=128) I want to add some extra fields in the Membership form that gets displayed through the Inline. These fields basically are a shortcut to the instantiation of another model (Trip). Trip can have its own admin views, but these shortcuts are needed because when my project partners are entering 'Membership' data in the system they happen to have also the 'Trip' information handy (and also because some of the info in Membership can just be copied over to Trip etc. etc.). So all I want to have is two extra fields in the Membership Inline - placeVisited and pleasuretrip - which together with the Person instance will let me instantiate the Trip model in the background... I found out I can easily add extra fields to the inline view by defining my own form. But once the data have been entered, how and when to reference to them in order to perform the save operations I need to do? class MyForm(forms.ModelForm): place = forms.ModelChoiceField(required=False, queryset=Place.objects.all(), label="place",) pleasuretrip = forms.BooleanField(required=False, label="...") class MembershipInline(admin.TabularInline): model = Membership form = MyForm def save_model(self, request, obj, form, change): place = form.place pleasuretrip = form.pleasuretrip person = form.person .... # now I can create Trip instances with those data .... obj.save() class GroupAdmin(admin.ModelAdmin): model = Group .... inlines = (MembershipInline,) This doesn't seem to work... I'm also a bit puzzled by the save_formset method... maybe is that the one I should be using? Many thanks in advance for the help!!!!

    Read the article

  • Reverse mapping from a table to a model in SQLAlchemy

    - by Jace
    To provide an activity log in my SQLAlchemy-based app, I have a model like this: class ActivityLog(Base): __tablename__ = 'activitylog' id = Column(Integer, primary_key=True) activity_by_id = Column(Integer, ForeignKey('users.id'), nullable=False) activity_by = relation(User, primaryjoin=activity_by_id == User.id) activity_at = Column(DateTime, default=datetime.utcnow, nullable=False) activity_type = Column(SmallInteger, nullable=False) target_table = Column(Unicode(20), nullable=False) target_id = Column(Integer, nullable=False) target_title = Column(Unicode(255), nullable=False) The log contains entries for multiple tables, so I can't use ForeignKey relations. Log entries are made like this: doc = Document(name=u'mydoc', title=u'My Test Document', created_by=user, edited_by=user) session.add(doc) session.flush() # See note below log = ActivityLog(activity_by=user, activity_type=ACTIVITY_ADD, target_table=Document.__table__.name, target_id=doc.id, target_title=doc.title) session.add(log) This leaves me with three problems: I have to flush the session before my doc object gets an id. If I had used a ForeignKey column and a relation mapper, I could have simply called ActivityLog(target=doc) and let SQLAlchemy do the work. Is there any way to work around needing to flush by hand? The target_table parameter is too verbose. I suppose I could solve this with a target property setter in ActivityLog that automatically retrieves the table name and id from a given instance. Biggest of all, I'm not sure how to retrieve a model instance from the database. Given an ActivityLog instance log, calling self.session.query(log.target_table).get(log.target_id) does not work, as query() expects a model as parameter. One workaround appears to be to use polymorphism and derive all my models from a base model which ActivityLog recognises. Something like this: class Entity(Base): __tablename__ = 'entities' id = Column(Integer, primary_key=True) title = Column(Unicode(255), nullable=False) edited_at = Column(DateTime, onupdate=datetime.utcnow, nullable=False) entity_type = Column(Unicode(20), nullable=False) __mapper_args__ = {'polymorphic_on': entity_type} class Document(Entity): __tablename__ = 'documents' __mapper_args__ = {'polymorphic_identity': 'document'} body = Column(UnicodeText, nullable=False) class ActivityLog(Base): __tablename__ = 'activitylog' id = Column(Integer, primary_key=True) ... target_id = Column(Integer, ForeignKey('entities.id'), nullable=False) target = relation(Entity) If I do this, ActivityLog(...).target will give me a Document instance when it refers to a Document, but I'm not sure it's worth the overhead of having two tables for everything. Should I go ahead and do it this way?

    Read the article

  • Django: Applying Calculations To A Query Set

    - by TheLizardKing
    I have a QuerySet that I wish to pass to a generic view for pagination: links = Link.objects.annotate(votes=Count('vote')).order_by('-created')[:300] This is my "hot" page which lists my 300 latest submissions (10 pages of 30 links each). I want to now sort this QuerySet by an algorithm that HackerNews uses: (p - 1) / (t + 2)^1.5 p = votes minus submitter's initial vote t = age of submission in hours Now because applying this algorithm over the entire database would be pretty costly I am content with just the last 300 submissions. My site is unlikely to be the next digg/reddit so while scalability is a plus it is required. My question is now how do I iterate over my QuerySet and sort it by the above algorithm? For more information, here are my applicable models: class Link(models.Model): category = models.ForeignKey(Category, blank=False, default=1) user = models.ForeignKey(User) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) url = models.URLField(max_length=1024, unique=True, verify_exists=True) name = models.CharField(max_length=512) def __unicode__(self): return u'%s (%s)' % (self.name, self.url) class Vote(models.Model): link = models.ForeignKey(Link) user = models.ForeignKey(User) created = models.DateTimeField(auto_now_add=True) def __unicode__(self): return u'%s vote for %s' % (self.user, self.link) Notes: I don't have "downvotes" so just the presence of a Vote row is an indicator of a vote or a particular link by a particular user.

    Read the article

  • How to filter Many2Many / Generic Relations properly with Q?

    - by HWM-Rocker
    Hi, I have 3 Models, the TaggedObject has a GenericRelation with the ObjectTagBridge. And the ObjectTagBridge has a ForeignKey to the Tag Model. class TaggedObject(models.Model): """ class that represent a tagged object """ tags = generic.GenericRelation('ObjectTagBridge', blank=True, null=True) class ObjectTagBridge(models.Model): """ Help to connect a generic object to a Tag. """ # pylint: disable-msg=W0232,R0903 content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey('content_type', 'object_id') tag = models.ForeignKey('Tag') class Tag(models.Model): ... when I am attaching a Tag to an Object, I am creating a new ObjectTagBridge and set its ForeignKey tag to the Tag I want to attach. That is working fine, and I can get all Tags that I attached to my Object very easy. But when I want to get (filter) all Objects that have Tag1 and Tag2 I tried to something like this: query = Q(tags__tag=Tag1) & Q(tags__tag=Tag2) object_list = TaggedObjects.filter(query) but now my object_list is empty, because it is looking for TaggedObjects that have one ObjectTagBridge with 2 tag objects, the first with Tag1 and the second with Tag2. I my application will be more complex Q queries than this one, so I think I need a solution with this Q object. In fact any combination of binary conjunctions, like: (...) and ( (...) or not(...)) How can I filter this correctly? Every answer is welcome, maybe there is also a different way do achieve this. thx for your help!!!

    Read the article

  • Django: Determining if a user has voted or not

    - by TheLizardKing
    I have a long list of links that I spit out using the below code, total votes, submitted by, the usual stuff but I am not 100% on how to determine if the currently logged in user has voted on a link or not. I know how to do this from within my view but do I need to alter my below view code or can I make use of the way templates work to determine it? I have read http://stackoverflow.com/questions/1528583/django-vote-up-down-method but I don't quite understand what's going on ( and don't need any ofjavascriptery). Models (snippet): class Link(models.Model): category = models.ForeignKey(Category, blank=False, default=1) user = models.ForeignKey(User) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) url = models.URLField(max_length=1024, unique=True, verify_exists=True) name = models.CharField(max_length=512) def __unicode__(self): return u'%s (%s)' % (self.name, self.url) class Vote(models.Model): link = models.ForeignKey(Link) user = models.ForeignKey(User) created = models.DateTimeField(auto_now_add=True) def __unicode__(self): return u'%s vote for %s' % (self.user, self.link) Views (snippet): def hot(request): links = Link.objects.select_related().annotate(votes=Count('vote')).order_by('-created') for link in links: delta_in_hours = (int(datetime.now().strftime("%s")) - int(link.created.strftime("%s"))) / 3600 link.popularity = ((link.votes - 1) / (delta_in_hours + 2)**1.5) if request.user.is_authenticated(): try: link.voted = Vote.objects.get(link=link, user=request.user) except Vote.DoesNotExist: link.voted = None links = sorted(links, key=lambda x: x.popularity, reverse=True) links = paginate(request, links, 15) return direct_to_template( request, template = 'links/link_list.html', extra_context = { 'links': links, }) The above view actually accomplishes what I need but in what I believe to be a horribly inefficient way. This causes the dreaded n+1 queries, as it stands that's 33 queries for a page containing just 29 links while originally I got away with just 4 queries. I would really prefer to do this using Django's ORM or at least .extra(). Any advice?

    Read the article

  • Django Aggregation Across Reverse Relationship

    - by Tom
    Given these two models: class Profile(models.Model): user = models.ForeignKey(User, unique=True, verbose_name=_('user')) about = models.TextField(_('about'), blank=True) zip = models.CharField(max_length=10, verbose_name='zip code', blank=True) website = models.URLField(_('website'), blank=True, verify_exists=False) class ProfileView(models.Model): profile = models.ForeignKey(Profile) viewer = models.ForeignKey(User, blank=True, null=True) created = models.DateTimeField(auto_now_add=True) I want to get all profiles sorted by total views. I can get a list of profile ids sorted by total views with: ProfileView.objects.values('profile').annotate(Count('profile')).order_by('-profile__count') But that's just a dictionary of profile ids, which means I then have to loop over it and put together a list of profile objects. Which is a number of additional queries and still doesn't result in a QuerySet. At that point, I might as well drop to raw SQL. Before I do, is there a way to do this from the Profile model? ProfileViews are related via a ForeignKey field, but it's not as though the Profile model knows that, so I'm not sure how to tie the two together. As an aside, I realize I could just store views as a property on the Profile model and that may turn out to be what I do here, but I'm still interested in learning how to better use the Aggregation functions.

    Read the article

  • Using map() on a _set in a template?

    - by Stuart Grimshaw
    I have two models like this: class KPI(models.Model): """KPI model to hold the basic info on a Key Performance Indicator""" title = models.CharField(blank=False, max_length=100) description = models.TextField(blank=True) target = models.FloatField(blank=False, null=False) group = models.ForeignKey(KpiGroup) subGroup = models.ForeignKey(KpiSubGroup, null=True) unit = models.TextField(blank=True) owner = models.ForeignKey(User) bt_measure = models.BooleanField(default=False) class KpiHistory(models.Model): """A historical log of previous KPI values.""" kpi = models.ForeignKey(KPI) measure = models.FloatField(blank=False, null=False) kpi_date = models.DateField() and I'm using RGraph to display the stats on internal wallboards, the handy thing is Python lists get output in a format that Javascript sees as an array, so by mapping all the values into a list like this: def f(x): return float(x.measure) stats = map(f, KpiHistory.objects.filter(kpi=1) then in the template I can simply use {{ stats }} and the RGraph code sees it as an array which is exactly what I want. [87.0, 87.5, 88.5, 90] So my question is this, is there any way I can achieve the same effect using Django's _set functionality to keep the amount of data I'm passing into the template, up until now I've been passing in a single KPI object to be graphed but now I want to pass in a whole bunch so is there anything I can do with _set {{ kpi.kpihistory_set }} dumps the whole model out, but I just want the measure field. I can't see any of the built in template methods that will let me pull out just the single field I want. How have other people handled this situation?

    Read the article

  • Performance Problems with Django's F() Object

    - by JayhawksFan93
    Has anyone else noticed performance issues using Django's F() object? I am running Windows XP SP3 and developing against the Django trunk. A snippet of the models I'm using and the query I'm building are below. When I have the F() object in place, each call to a QuerySet method (e.g. filter, exclude, order_by, distinct, etc.) takes approximately 2 seconds, but when I comment out the F() clause the calls are sub-second. I had a co-worker test it on his Ubuntu machine, and he is not experiencing the same performance issues I am with the F() clause. Anyone else seeing this behavior? class Move (models.Model): state_meaning = models.CharField( max_length=16, db_index=True, blank=True, default='' ) drop = models.ForeignKey( Org, db_index=True, null=False, default=1, related_name='as_move_drop' ) class Split(models.Model): state_meaning = models.CharField( max_length=16, db_index=True, blank=True, default='' ) move = models.ForeignKey( Move, related_name='splits' ) pickup = models.ForeignKey( Org, db_index=True, null=False, default=1, related_name='as_split_pickup' ) pickup_date = models.DateField( null=True, default=None ) drop = models.ForeignKey( Org, db_index=True, null=False, default=1, related_name='as_split_drop' ) drop_date = models.DateField( null=True, default=None, db_index=True ) def get_splits(begin_date, end_date): qs = Split.objects \ .filter(state_meaning__in=['INPROGRESS','FULFILLED'], drop=F('move__drop'), # <<< the line in question pickup_date__lte=end_date) elapsed = timer.clock() - start print 'qs1 took %.3f' % elapsed start = timer.clock() qs = qs.filter(Q(drop_date__gte=begin_date) | Q(drop_date__isnull=True)) elapsed = timer.clock() - start print 'qs2 took %.3f' % elapsed start = timer.clock() qs = qs.exclude(move__state_meaning='UNFULFILLED') elapsed = timer.clock() - start print 'qs3 took %.3f' % elapsed start = timer.clock() qs = qs.order_by('pickup_date', 'drop_date') elapsed = timer.clock() - start print 'qs7 took %.3f' % elapsed start = timer.clock() qs = qs.distinct() elapsed = timer.clock() - start print 'qs8 took %.3f' % elapsed

    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

  • How to convert this query to a "django model query" ?

    - by fabriciols
    Hello ! What i want is simple : models : class userLastTrophy(models.Model): user = models.ForeignKey(userInfo) platinum = models.IntegerField() gold = models.IntegerField() silver = models.IntegerField() bronze = models.IntegerField() level = models.IntegerField() rank = models.IntegerField() perc_level = models.IntegerField() date_update = models.DateTimeField(default=datetime.now, blank=True) total = models.IntegerField() points = models.IntegerField() class userTrophy(models.Model): user = models.ForeignKey(userInfo) platinum = models.IntegerField() gold = models.IntegerField() silver = models.IntegerField() bronze = models.IntegerField() total = models.IntegerField() level = models.IntegerField() perc_level = models.IntegerField() date_update = models.DateTimeField(default=datetime.now, blank=True) rank = models.IntegerField(default=0) total = models.IntegerField(default=0) points = models.IntegerField(default=0) last_trophy = models.ForeignKey(userLastTrophy, default=0) I have this query : select t2.user_id as id, t2.platinum - t1.platinum as plat, t2.gold - t1.gold as gold, t2.silver - t1.silver as silver, t2.bronze - t1.bronze as bronze, t2.points - t1.points as points from myps3t_usertrophy t2, myps3t_userlasttrophy t1 where t1.id = t2.last_trophy_id order by points; how to do this with django models ?

    Read the article

  • Filter Queryset in Django inlineformset_factory

    - by Dave
    I am trying to use inlineformset_factory to generate a formset. My models are defined as: class Measurement(models.Model): subject = models.ForeignKey(Animal) experiment = models.ForeignKey(Experiment) assay = models.ForeignKey(Assay) values = models.CommaSeparatedIntegerField(blank=True, null=True) class Experiment(models.Model): date = models.DateField() notes = models.TextField(max_length = 500, blank=True) subjects= models.ManyToManyField(Subject) in my view i have: def add_measurement(request, experiment_id): experiment = get_object_or_404(Experiment, pk=experiment_id) MeasurementFormSet = inlineformset_factory(Experiment, Measurement, extra=10, exclude=('experiment')) if request.method == 'POST': formset = MeasurementFormSet(request.POST,instance=experiment) if formset.is_valid(): formset.save() return HttpResponseRedirect( experiment.get_absolute_url() ) else: formset = MeasurementFormSet(instance=experiment) return render_to_response("data_entry_form.html", {"formset": formset, "experiment": experiment }, context_instance=RequestContext(request)) but i want to restrict the Measurement.subject field to only subjects defined in the Experiment.subjects queryset. I have tried a couple of different ways of doing this but I am a little unsure what the best way to accomplish this is. I tried to over-ride the BaseInlineFormset class with a new queryset, but couldnt figure out how to correctly pass the experiment parameter.

    Read the article

  • Inline editing of ManyToMany relation in Django

    - by vorpyg
    After working through the Django tutorial I'm now trying to build a very simple invoicing application. I want to add several Products to an Invoice, and to specify the quantity of each product in the Invoice form in the Django admin. Now I've to create a new Product object if I've got different quantites of the same Product. Right now my models look like this (Company and Customer models left out): class Product(models.Model): description = models.TextField() quantity = models.IntegerField() price = models.DecimalField(max_digits=10,decimal_places=2) tax = models.ForeignKey(Tax) class Invoice(models.Model): company = models.ForeignKey(Company) customer = models.ForeignKey(Customer) products = models.ManyToManyField(Product) invoice_no = models.IntegerField() invoice_date = models.DateField(auto_now=True) due_date = models.DateField(default=datetime.date.today() + datetime.timedelta(days=14)) I guess the quantity should be left out of the Product model, but how can I make a field for it in the Invoice model?

    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 foreign keys cascade deleting and "related_name" parameter (bug?)

    - by Wiseman
    In this topic I found a good way to prevent cascade deleting of relating objects, when it's not neccessary. class Factures(models.Model): idFacture = models.IntegerField(primary_key=True) idLettrage = models.ForeignKey('Lettrage', db_column='idLettrage', null=True, blank=True) class Paiements(models.Model): idPaiement = models.IntegerField(primary_key=True) idLettrage = models.ForeignKey('Lettrage', db_column='idLettrage', null=True, blank=True) class Lettrage(models.Model): idLettrage = models.IntegerField(primary_key=True) def delete(self): """Dettaches factures and paiements from current lettre before deleting""" self.factures_set.clear() self.paiements_set.clear() super(Lettrage, self).delete() But this method seems to fail when we are using ForeignKey field with "related_name" parameter. As it seems to me, "clear()" method works fine and saves the instance of "deassociated" object. But then, while deleting, django uses another memorized copy of this very object and since it's still associated with object we are trying to delete - whooooosh! ...bye-bye to relatives :) Database was arcitectured before me, and in somewhat odd way, so I can't escape these "related_names" in reasonable amount of time. Anybody heard about workaround for such a trouble?

    Read the article

  • How to limit choice field options based on another choice field in django admin

    - by umnik700
    I have the following models: class Category(models.Model): name = models.CharField(max_length=40) class Item(models.Model): name = models.CharField(max_length=40) category = models.ForeignKey(Category) class Demo(models.Model): name = models.CharField(max_length=40) category = models.ForeignKey(Category) item = models.ForeignKey(Item) In the admin interface when creating a new Demo, after user picks category from the dropdown, I would like to limit the number of choices in the "items" drop-down. If user selects another category then the item choices should update accordingly. I would like to limit item choices right on the client, before it even hits the form validation on the server. This is for usability, because the list of items could be 1000+ being able to narrow it down by category would help to make it more manageable. Is there a "django-way" of doing it or is custom JavaScript the only option here?

    Read the article

  • django left join with null

    - by SledgehammerPL
    The model: class Product(models.Model): name = models.CharField(max_length = 128) def __unicode__(self): return self.name class Receipt(models.Model): name = models.CharField(max_length=128) components = models.ManyToManyField(Product, through='ReceiptComponent') class Admin: pass def __unicode__(self): return self.name class ReceiptComponent(models.Model): product = models.ForeignKey(Product) receipt = models.ForeignKey(Receipt) quantity = models.FloatField(max_length=9) unit = models.ForeignKey(Unit) def __unicode__(self): return unicode(self.quantity!=0 and self.quantity or '') + ' ' + unicode(self.unit) + ' ' + self.product.genitive The idea: there are a components on stock. I'd like to find out which recipes I can made with components which I have. It's not easy - but possible - I made a SQL view, which gets the solution. But I'm learning python and Django so I'd like to make it Django-style ;D The concept of solution: get the set of recipes which has at last one component: list_of_available_components = ReceiptComponent.objects.filter(product__in=list_of_available_products).distinct() list_of_related_receipts = Receipt.objects.filter(receiptcomponent__in = list_of_available_components).distinct() get recipes (from list_of_related_receipts) which has not at last one component list_of_incomplete_recipes = (SELECT * FROM drinkbook_receiptcomponent LEFT JOIN drinkstore_stock_products USING(product_id) WHERE drinkstore_stock_products.stock_id IS NULL AND receipt_id IN (SELECT receipt_id FROM drinkbook_receiptcomponent JOIN drinkstore_stock_products USING(product_id))) get recipes (from list_of_related_receipts) which are not in "list_of_incomplete_recipes"

    Read the article

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