Search Results

Search found 126 results on 6 pages for 'manytomanyfield'.

Page 1/6 | 1 2 3 4 5 6  | Next Page >

  • manyToManyField question

    - by dotty
    Hay guys, I'm writing a simple app which logs recipes. I'm working out my models and have stumbled across a problem My Dish models needs to have many Ingredients. This is no problem because i would do something like this ingredients = models.ManyToManyfield(Ingredient) No problems, my dish now can have many ingrendients. However, the problem is that the ingredient needs to come in different quantities. I.E 4 eggs, 7 tablespoons sugar My Ingredient Model is very simple at the moment class Ingredient(models.Model): name = models.TextField(blank=False) slug = models.SlugField(blank=True) How would i go about work out this problem? What fields would i need to add, would i need to use a 'through' attribute on my ManyToManyfield to solve this problem?

    Read the article

  • Django Cannot set values on a ManyToManyField which specifies an intermediary model

    - by dana
    i am using a m2m and a through table, and when i was trying to save, my error was: Cannot set values on a ManyToManyField which specifies an intermediary model so, i've modified my code, so that when i save the form, to insert data into the 'through' table too.But now, i'm having another error. (i've bolded the lines where i think i am wrong) i have in models.py: class Classroom(models.Model): user = models.ForeignKey(User, related_name = 'classroom_creator') classname = models.CharField(max_length=140, unique = True) date = models.DateTimeField(auto_now=True) open_class = models.BooleanField(default=True) members = models.ManyToManyField(User,related_name="list of invited members", through = 'Membership') class Membership(models.Model): accept = models.BooleanField(User) date = models.DateTimeField(auto_now = True) classroom = models.ForeignKey(Classroom, related_name = 'classroom_membership') member = models.ForeignKey(User, related_name = 'user_membership') and in def save_classroom(request): if request.method == 'POST': form = ClassroomForm(request.POST, request.FILES, user = request.user) **classroom_instance = Classroom member_instance = Membership** if form.is_valid(): new_obj = form.save(commit=False) new_obj.user = request.user r = Relations.objects.filter(initiated_by = request.user) membership = Membership.objects.create(**classroom = classroom_instance, member = member_instance,date=datetime.datetime.now())** new_obj.save() form.save_m2m() return HttpResponseRedirect('/classroom/classroom_view/{{user}}/') else: form = ClassroomForm(user = request.user) return render_to_response('classroom/classroom_form.html', { 'form': form, }, context_instance=RequestContext(request)) but i don't seem to initialise okay the classroom_instance and menber_instance.My error os: Cannot assign "": "Membership.classroom" must be a "Classroom" instance. Thanks!

    Read the article

  • Validation on ManyToManyField before Save in Models.py

    - by Heyl1
    I have the following models: class Application(models.Model): users = models.ManyToManyField(User, through='Permission') folder = models.ForeignKey(Folder) class Folder(models.Model): company = models.ManyToManyField(Compnay) class UserProfile(models.Model): user = models.OneToOneField(User, related_name='profile') company = models.ManyToManyField(Company) What I would like to do is to check whether one of the users of the Application has the same company as the Application (via Folder). If this is the case the Application instance should not be saved. The problem is that the ManyToManyFields aren't updated until after the 'post-save' signal. The only option seems to be the new m2m_changed signal. But I'm not sure how I then roll back the save that has already happened. Another option would be to rewrite the save function (in models.py, because I'm talking about the admin here), but I'm not sure how I could access the manytomanyfield content. Finally I've read something about rewriting the save function in the admin of the model in admin.py, however I still wouldn't know how you would access the manytomanyfield content. I have been searching for this everywhere but nothing I come across seems to work for me. If anything is unclear, please tell me. Thanks for your help! Heleen

    Read the article

  • Django: query with ManyToManyField count?

    - by AP257
    In Django, how do I construct a COUNT query for a ManyToManyField? My models are as follows, and I want to get all the people whose name starts with A and who are the lord or overlord of at least one Place, and order the results by name. class Manor(models.Model): lord = models.ManyToManyField(Person, null=True, related_name="lord") overlord = models.ManyToManyField(Person, null=True, related_name="overlord") class Person(models.Model): name = models.CharField(max_length=100) So my query should look something like this... but how do I construct the third line? people = Person.objects.filter( Q(name__istartswith='a'), Q(lord.count > 0) | Q(overlord.count > 0) # pseudocode ).order_by('name'))

    Read the article

  • Creating a QuerySet based on a ManyToManyField in Django

    - by River Tam
    So I've got two classes; Picture and Tag that are as follows: class Tag(models.Model): pics = models.ManyToManyField('Picture', blank=True) name = models.CharField(max_length=30) # stuff omitted class Picture(models.Model): name = models.CharField(max_length=100) pub_date = models.DateTimeField('date published') tags = models.ManyToManyField('Tag', blank=True) content = models.ImageField(upload_to='instaton') #stuff omitted And what I'd like to do is get a queryset (for a ListView) given a tag name that contains the most recent X number of Pictures that are tagged as such. I've looked up very similar problems, but none of the responses make any sense to me at all. How would I go about creating this queryset?

    Read the article

  • Show models.ManyToManyField as inline, with the same form as models.ForeignKey inline

    - by Kristian
    I have a model similar to the following (simplified): models.py class Sample(models.Model): name=models.CharField(max_length=200) class Action(models.Model): samples=models.ManyToManyField(Sample) title=models.CharField(max_length=200) description=models.TextField() Now, if Action.samples would have been a ForeignKey instead of a ManyToManyField, when I display Action as a TabularInline in Sample in the Django Admin, I would get a number of rows, each containing a nice form to edit or add another Action. However; when I display the above as an inline using the following: class ActionInline(admin.TabularInline): model=Action.samples.through I get a select box listing all available actions, and not a nifty form to create a new Action. My question is really: How do I display the ManyToMany relation as an inline with a form to input information as described? In principle it should be possible since, from the Sample's point of view, the situation is identical in both cases; Each Sample has a list of Actions regardless if the relation is a ForeignKey or a ManyToManyRelation. Also; Through the Sample admin page, I never want to choose from existing Actions, only create new or edit old ones.

    Read the article

  • Django filters - Using an AllValuesFilter (with a LinkWidget) on a ManyToManyField

    - by magnetix
    This is my first Stack Overflow question, so please let me know if I do anything wrong. I wish to create an AllValues filter on a ManyToMany field using the wonderful django-filters application. Basically, I want to create a filter that looks like it does in the Admin, so I also want to use the LinkWidget too. Unfortunately, I get an error (Invalid field name: 'operator') if I try this the standard way: # Models class Organisation(models.Model): name = models.CharField() ... class Sign(models.Model): name = models.CharField() operator = models.ManyToManyField('Organisation', blank=True) ... # Filter class SignFilter(LinkOrderFilterSet): operator = django_filters.AllValuesFilter(widget=django_filters.widgets.LinkWidget) class Meta: model = Sign fields = ['operator'] I got around this by creating my own filter with the many to many relationship hard coded: # Models class Organisation(models.Model): name = models.CharField() ... class Sign(models.Model): name = models.CharField() operator = models.ManyToManyField('Organisation', blank=True) ... # Filter class MyFilter(django_filters.ChoiceFilter): @property def field(self): cd = {} for row in self.model.objects.all(): orgs = row.operator.select_related().values() for org in orgs: cd[org['id']] = org['name'] choices = zip(cd.keys(), cd.values()) list.sort(choices, key=lambda x:(x[1], x[0])) self.extra['choices'] = choices return super(AllValuesFilter, self).field class SignFilter(LinkOrderFilterSet): operator = MyFilter(widget=django_filters.widgets.LinkWidget) I am new to Python and Django. Can someone think of a more generic/elegant way of doing this?

    Read the article

  • Delete manytomanyfield in Django

    - by Mike
    I have the following models class Database(models.Model): user = models.ForeignKey(User) name = models.CharField(max_length=100) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class DatabaseUser(models.Model): user = models.ForeignKey(User) name = models.CharField(max_length=100) password = models.CharField(max_length=100) database = models.ManyToManyField(Database) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) One DatabaseUser can have many Databases under it's control. The issue I have if I go to delete a Database it wants to Delete the DatabaseUser also.. Is there a way to stop this from happening easily?

    Read the article

  • Django: Prefill a ManytoManyField

    - by Emile Petrone
    I have a ManyToManyField on a settings page that isn't rendering. The data was filled when the user registered, and I am trying to prefill that data when the user tries to change it. Thanks in advance for the help! The HTML: {{form.types.label}} {% if add %} {{form.types}} {% else %} {% for type in form.types.all %} {{type.description}} {% endfor %} {% endif %} The View: @csrf_protect @login_required def edit_host(request, host_id, template_name="host/newhost.html"): host = get_object_or_404(Host, id=host_id) if request.user != host.user: return HttpResponseForbidden() form = HostForm(request.POST) if form.is_valid(): if request.method == 'POST': if form.cleaned_data.get('about') is not None: host.about = form.cleaned_data.get('about') if form.cleaned_data.get('types') is not None: host.types = form.cleaned_data.get('types') host.save() form.save_m2m() return HttpResponseRedirect('/users/%d/' % host.user.id) else: form = HostForm(initial={ "about":host.about, "types":host.types, }) data = { "host":host, "form":form } return render_to_response(template_name, data, context_instance=RequestContext(request)) Form: class HostForm(forms.ModelForm): class Meta: model = Host fields = ('types', 'about', ) types = forms.ModelMultipleChoiceField( widget=forms.CheckboxSelectMultiple, queryset=Type.objects.all(), required=True) about = forms.CharField( widget=forms.Textarea(), required=True) def __init__(self, *args, **kwargs): super(HostForm, self).__init__(*args, **kwargs) self.fields['about'].widget.attrs = { 'placeholder':'Hello!'}

    Read the article

  • Django show manytomanyfield on form when definition is on other model

    - by John
    Hi I have the definition for my manytomany relationship on one model but want to display the field on a form for the other model. How do I do this? for example: # classes class modelA(models.Model): name = models.CharField(max_length=300) manytomany = models.ManyToManyField(modelA) class modelB(models.Model): name = models.CharField(max_length=300) # forms class modelBForm(forms.ModelForm): class Meta: model = modelB I want to use the form modelBForm but show a select box with a list from modelA (just how it would work if the model was set to modelA in the form class). How can I do this? Thanks

    Read the article

  • Django Admin: Many-to-Many listbox doesn't show up with a through parameter

    - by NP
    Hi All, I have the following models: class Message(models.Model): date = models.DateTimeField() user = models.ForeignKey(User) thread = models.ForeignKey('self', blank=True, null=True) ... class Forum(models.Model): name = models.CharField(max_length=24) messages = models.ManyToManyField(Message, through="Message_forum", blank=True, null=True) ... class Message_forum(models.Model): message = models.ForeignKey(Message) forum = models.ForeignKey(Forum) status = models.IntegerField() position = models.IntegerField(blank=True, null=True) tags = models.ManyToManyField(Tag, blank=True, null=True) In the admin site, when I go to add/change a forum, I don't see the messages listbox as you'd expect. However, it shows up if I remove the 'through' parameter in the ManyToManyField declaration. What's up with that? I've registered all three models (plus Tag) to the admin site in admin.py. TIA

    Read the article

  • listing objects from ManyToManyField

    - by Noam Smadja
    i am trying to print a list of all the Conferences and for each conference, print its 3 Speakers. in my template i have: {% if conferences %} <ul> {% for conference in conferences %} <li>{{ conference.date }}</li> {% for speakers in conference.speakers %} <li>{{ conference.speakers }}</li> {% endfor %} {% endfor %} </ul> {% else %} <p>No Conferences</p> {% endif %} in my views.py file i have: from django.shortcuts import render_to_response from youthconf.conference.models import Conference def manageconf(request): conferences = Conference.objects.all().order_by('-date')[:5] return render_to_response('conference/manageconf.html', {'conferences': conferences}) there is a model named conference. which has a class named Conferences with a ManyToManyField named speakers i get the error: Caught an exception while rendering: 'ManyRelatedManager' object is not iterable with this line: {% for speakers in conference.speakers %}

    Read the article

  • ManyToManyField "table exist" error on syncdb

    - by Derek Reynolds
    When I include a ModelToModelField to one of my models the following error is thrown. Traceback (most recent call last): File "manage.py", line 11, in <module> execute_manager(settings) File "/Library/Python/2.6/site-packages/django/core/management/__init__.py", line 362, in execute_manager utility.execute() File "/Library/Python/2.6/site-packages/django/core/management/__init__.py", line 303, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Library/Python/2.6/site-packages/django/core/management/base.py", line 195, in run_from_argv self.execute(*args, **options.__dict__) File "/Library/Python/2.6/site-packages/django/core/management/base.py", line 222, in execute output = self.handle(*args, **options) File "/Library/Python/2.6/site-packages/django/core/management/base.py", line 351, in handle return self.handle_noargs(**options) File "/Library/Python/2.6/site-packages/django/core/management/commands/syncdb.py", line 93, in handle_noargs cursor.execute(statement) File "/Library/Python/2.6/site-packages/django/db/backends/util.py", line 19, in execute return self.cursor.execute(sql, params) File "/Library/Python/2.6/site-packages/django/db/backends/mysql/base.py", line 84, in execute return self.cursor.execute(query, args) File "build/bdist.macosx-10.6-universal/egg/MySQLdb/cursors.py", line 173, in execute File "build/bdist.macosx-10.6-universal/egg/MySQLdb/connections.py", line 36, in defaulterrorhandler _mysql_exceptions.OperationalError: (1050, "Table 'orders_proof_approved_associations' already exists") Field definition: approved_associations = models.ManyToManyField(Association) Everything works fine when I remove the field, and the table is no where in site. Any thoughts as to why this would happen?

    Read the article

  • Alternate widgets and logic for ManyToManyField with Django forms

    - by Jaearess
    In my Django project, I have a simple ticket system. When creating a ticket, certain users have the ability to assign the ticket to other users, and to email the ticket to other users as well (this is used as an FYI for those users, so they're aware of the ticket, even though it's not assigned to them.) At the moment, the form for adding a ticket is simply the default Django form, with the "assigned_to" and "email_to" fields being ManyToManyFields, and therefore displayed as MultipleSelect widgets, each with a list of all users. Due to the relatively large number of users, and general awkwardness of the MultipleSelect widget, and alternate layout is now required. The desired layout is a pair of simple Select widgets side-by-side. The first has the option of "Assign to" or "Email to" and the second is a list of the users. Essentially, like this: [Assign to] [John Doe] [Email to] [Jane Roe] [Jack Smith], etc. Of course, since an arbitrary number of users can be assigned or emailed a ticket, there's a simple button that runs some Javascript to add another set of widgets, to allow the user to assign and email as many people as they need to. So far all of that is fairly simple and straight forward. However, the problem I have is using this widget setup/logic setup with Django forms. Instead of lists of users to assign to and email, instead we're getting back pairs of information, one a user and the other which list that user should be placed in. What I'm looking for, but have yet to find, is a way to offload the translation between how the user uses the form, and how Django understands the model to the form itself, so I don't have to manually do the processing of the data before passing it to the form in each place this form is used. Additionally, there's a review screen with the option to go back and change the form before submitting it, so a way to have the form translate both to and from this format would be extremely helpful.

    Read the article

  • How to limit manytomanyfields on a model ?

    - by Tom
    I would like to check that I get not more than 3 relations set on a manytomanyfield. I tried on the clean method to do this : if self.tags.count()>3: raise ValidationError(_(u'You cannot add more than 3 tags')) But self.tags returns not the current updates... only saved objects. Do you have an idea to access to them ? Thanks

    Read the article

  • django-admin: creating,saving and relating a m2m model

    - by pastylegs
    I have two models: class Production(models.Model): gallery = models.ManyToManyField(Gallery) class Gallery(models.Model): name = models.CharField() I have the m2m relationship in my productions admin, but I want that functionality that when I create a new Production, a default gallery is created and the relationship is registered between the two. So far I can create the default gallery by overwriting the productions save: def save(self, force_insert=False, force_update=False): if not ( Gallery.objects.filter(name__exact="foo").exists() ): g = Gallery(name="foo") g.save() self.gallery.add(g) This creates and saves the model instance (if it doesn't already exist), but I don't know how to register the relationship between the two?

    Read the article

  • How to get Media Picker Field via proxy record of many-to-many in orchard

    - by Sergey Schipanov
    I need to access mediapickerfield in Widget view. This field is relative to 'ActionPart'. I have a problem, when I create many-to-many relationships to display my 'ActionPart' in the widget. When I mapped many-to-many I take an 'ActionPart' and but cannot access the mediapickerfield. Records classes public class ActionPartRecord : ContentPartRecord { public virtual string Text { get; set; } public virtual double Price { get; set; } public virtual int TextPosX { get; set; } public virtual int TextPosY { get; set; } public virtual String TextSale { get; set; } public virtual int Color { get; set; } } public class ActionListRecord { public virtual int Id { get; set; } public virtual ActionPartRecord ActionPartRecord { get; set; } public virtual ActionWidgetPartRecord ActionWidgetPartRecord { get; set; } } public class ActionWidgetPartRecord : ContentPartRecord { public ActionWidgetPartRecord() { ActionList = new List<ActionListRecord>(); } public virtual IList<ActionListRecord> ActionList { get; set; } } public class ActionWidgetPart : ContentPart<ActionWidgetPartRecord> { public IEnumerable<ActionPartRecord> ActionList { get { return Record.ActionList.Select(x => x.ActionPartRecord); } } } ActionPart class public class ActionPart : ContentPart<ActionPartRecord> { public String Text { get { return Record.Text; } set { Record.Text = value; } } /*other field*/ } Migrations public int Create() { SchemaBuilder.CreateTable("ActionPartRecord", table => table .ContentPartRecord() .Column<string>("Text") .Column<double>("Price") .Column<int>("TextPosX") .Column<int>("TextPosY") .Column<string>("TextSale") .Column<int>("Color") ); ContentDefinitionManager.AlterPartDefinition("ActionPart", builder => builder .WithField("BaseImage", fieldBuilder => fieldBuilder.OfType("MediaPickerField").WithDisplayName("Action Image")) .WithField("PatternImage", fieldBuilder => fieldBuilder.OfType("MediaPickerField").WithDisplayName("Pattern Image")) .WithField("TimeExp", fieldBuilder => fieldBuilder.OfType("DateTimeField").WithDisplayName("Expecting date")) .Attachable()); ContentDefinitionManager.AlterTypeDefinition("Action", cfg => cfg .WithPart("CommonPart") .WithPart("TitlePart") .WithPart("RoutePart") .WithPart("BodyPart") .WithPart("ActionPart") .Creatable() .Indexed()); SchemaBuilder.CreateTable("ActionListRecord", table => table .Column<int>("Id", column => column.PrimaryKey().Identity()) .Column<int>("ActionPartRecord_Id") .Column<int>("ActionWidgetPartRecord_Id") ); SchemaBuilder.CreateTable("ActionWidgetPartRecord", table => table .ContentPartRecord() ); ContentDefinitionManager.AlterPartDefinition( "ActionWidgetPart", builder => builder.Attachable()); ContentDefinitionManager.AlterTypeDefinition("ActionWidget", cfg => cfg .WithPart("ActionWidgetPart") .WithPart("WidgetPart") .WithPart("CommonPart") .WithSetting("Stereotype", "Widget")); return 1; } Driver Display method protected override DriverResult Display( ActionWidgetPart part, string displayType, dynamic shapeHelper) { return ContentShape("Parts_ActionWidget", () => shapeHelper.Parts_ActionWidget( ContentPart: part, ActionList: part.ActionList)); } Widget View @foreach (var action in Model.ActionList) { <div class="item"> *How to access BaseImage Field in this row* <div class="sale-pattern"></div> <div class="container"> <div class="carousel-caption"> <h1>@action.Text</h1> <h1 class="price">@action.Price</h1> </div> </div> </div> }

    Read the article

  • How can I access the "through" object of a Django ManyToManyField?

    - by Macha
    I have the following models in my Django app. How can I from the Team model find all the User objects who have accepted as True in the Membership model? I know I need to use Team.objects.filter(), but I'm not sure how to check the value of the accepted field. from django.contrib.auth.models import User class Team(models.Model): members = models.ManyToManyField(User, through="Membership") class Membership(models.Model): user = models.ForeignKey(User) team = models.ForeignKey(Team) accepted = models.BooleanField(default=False)

    Read the article

  • How do I prevent a ManyToManyField('self') from linked an object to itself?

    - by dyve
    Consider this model (simplified for this question): class SecretAgentName(models.Model): name = models.CharField(max_length=100) aliases = ManyToManyField('self') I have three names, "James Bond", "007" and "Jason Bourne". "James Bond" and "007" are aliases of each other. This works exactly like I want it to, except for the fact that every instance can also be an alias of itself. This I want to prevent. So, there can be many SecretAgentNames, all can be aliases of each other as long as "James Bond" does not show up as an alias for "James Bond". Can I prevent this in the model definition? If not, can I prevent it anywhere else, preferably so that the Django Admin understands it?

    Read the article

  • ManyToManyField error when having recursive structure. How to solve it?

    - by luc
    Hello, I have the following table in the model with a recursive structure (a page can have children pages) class DynamicPage(models.Model): name = models.CharField("Titre",max_length=200) parent = models.ForeignKey('self',null=True,blank=True) I want to create another table with manytomany relation with this one: class UserMessage(models.Model): name = models.CharField("Nom", max_length=100) page = models.ManyToManyField(DynamicPage) The generated SQL creates the following constraint: ALTER TABLE `website_dynamicpage` ADD CONSTRAINT `parent_id_refs_id_29c58e1b` FOREIGN KEY (`parent_id`) REFERENCES `website_dynamicpage` (`id`); I would like to have the ManyToMany with the page itself (the id) and not with the parent field. How to modify the model to make the constraint using the id and not the parent? Thanks in advance

    Read the article

  • How to add manytomany field to flatpage admin

    - by valya
    Hello! I have a site with Flatpages, and now I need to be able to add galleries (Gallery model) to the page. This is going to be ManyToManyField, so there is no need to change the flatpages table. But I still can't define ManyToManyField in proxy class. I can define ManyToManyField in Gallery model, but it isn't comfortable for the client. How can I change FlatPage Admin to add a ManyToManyField from Galleries model?

    Read the article

  • Limiting choices from an intermediary ManyToMany junction table in Django

    - by Matthew Rankin
    Background I've created three Django models—Inventory, SalesOrder, and Invoice—to model items in inventory, sales orders for those items, and invoices for a particular sales order. Each sales order can have multiple items, so I've used an intermediary junction table—SalesOrderItems—using the through argument for the ManyToManyField. Also, partial billing of a sales orders is allowed, so I've created a ForeignKey in the Invoice model related to the SalesOrder model, so that a particular sales order can have multiple invoices. Here's where I deviate from what I've normally seen. Instead of relating the Invoice model to the Item model via a ManyToManyField, I've related the Invoice model to the SalesOrderItem intermediary junction table through the intermediary junction table InvoiceItem. I've done this because it better models reality—our invoices are tied to sales orders and can only include items that are tied to that sales order as opposed to any item in inventory. I will admit that it does seem strange having the intermediary junction table of a ManyToManyField related to the intermediary junction table of another ManyToManyField. Question How can I limit the choices available for the invoice_items in the Invoice model to just the sales_order_items of the SalesOrder model for that particular Invoice? (I tried using limit_choices_to= {'sales_order': self.invoice.sales_order}) as part of the item = models.ForeignKey(SalesOrderItem) in the InvoiceItem model, but that didn't work. Am I correct in thinking that limiting the choices for the invoice_items should be handled in the model instead of in a form? Code class Item(models.Model): item_num = models.SlugField(unique=True) default_price = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True) class SalesOrderItem(models.Model): item = models.ForeignKey(Item) sales_order = models.ForeignKey('SalesOrder') unit_price = models.DecimalField(max_digits=10, decimal_places=2) quantity = models.DecimalField(max_digits=10, decimal_places=4) class SalesOrder(models.Model): customer = models.ForeignKey(Party) so_num = models.SlugField(max_length=40, unique=True) sales_order_items = models.ManyToManyField(Item, through=SalesOrderItem) class InvoiceItem(models.Model): item = models.ForeignKey(SalesOrderItem) invoice = models.ForeignKey('Invoice') unit_price = models.DecimalField(max_digits=10, decimal_places=2) quantity = models.DecimalField(max_digits=10, decimal_places=4) class Invoice(models.Model): invoice_num = models.SlugField(max_length=25) sales_order = models.ForeignKey(SalesOrder) invoice_items = models.ManyToManyField(SalesOrderItem, through='InvoiceItem')

    Read the article

  • Django models: Use multiple values as a key?

    - by Rosarch
    Here is a simple model: class TakingCourse(models.Model): course = models.ForeignKey(Course) term = models.ForeignKey(Term) Instead of Django creating a default primary key, I would like to use both course and term as the primary key - taken together, they uniquely identify a tuple. Is this allowed by Django? On a related note: I am trying to represent users taking courses in certain terms. Is there a better way to do this? class Course(models.Model): name = models.CharField(max_length=200) requiredFor = models.ManyToManyField(RequirementSubSet, blank=True) offeringSchool = models.ForeignKey(School) def __unicode__(self): return "%s at %s" % (self.name, self.offeringSchool) 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(TakingCourse, blank=True) school = models.ForeignKey(School) class TakingCourse(models.Model): course = models.ForeignKey(Course) term = models.ForeignKey(Term) class Term(models.Model): school = models.ForeignKey(School) isPrimaryTerm = models.BooleanField()

    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

1 2 3 4 5 6  | Next Page >