Search Results

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

Page 10/18 | < Previous Page | 6 7 8 9 10 11 12 13 14 15 16 17  | Next Page >

  • Django anonymous user in model

    - by jack
    I have a model defined as below: class Example(models.Model): user = models.ForeignKey(User, null=True) other = models.CharField(max_length=100) The problem is Django refuses to assign django.contrib.auth.models.AnonymousUser directly to Example.user as null field so everytime I have to check if request.user.is_authenticated() ans assign Example.user = None manually. Is there a default value for AnonymousUser to use in a model field?

    Read the article

  • Schema qualified tables with SQLAlchemy, SQLite and Postgresql?

    - by Chris Reid
    I have a Pylons project and a SQLAlchemy model that implements schema qualified tables: class Hockey(Base): __tablename__ = "hockey" __table_args__ = {'schema':'winter'} hockey_id = sa.Column(sa.types.Integer, sa.Sequence('score_id_seq', optional=True), primary_key=True) baseball_id = sa.Column(sa.types.Integer, sa.ForeignKey('summer.baseball.baseball_id')) This code works great with Postgresql but fails when using SQLite on table and foreign key names (due to SQLite's lack of schema support) sqlalchemy.exc.OperationalError: (OperationalError) unknown database "winter" 'PRAGMA "winter".table_info("hockey")' () I'd like to continue using SQLite for dev and testing. Is there a way of have this fail gracefully on SQLite?

    Read the article

  • jqgrid and django models

    - by Andrew Gee
    Hi, I have the following models class Employee(Person): job = model.Charfield(max_length=200) class Address(models.Model): street = models.CharField(max_length=200) city = models.CharField(max_length=200) class EmpAddress(Address): date_occupied = models.DateField() date_vacated = models.DateField() employee = models.ForeignKey() When I build a json data structure for an EmpAddress object using the django serialzer it does not include the inherited fields only the EmpAddress fields. I know the fields are available in the object in my view as I can print them but they are not built into the json structure. Does anyone know how to overcome this? Thanks Andrew

    Read the article

  • List of Django model instance foreign keys losing consistency during state changes.

    - by Joshua
    I have model, Match, with two foreign keys: class Match(model.Model): winner = models.ForeignKey(Player) loser = models.ForeignKey(Player) When I loop over Match I find that each model instance uses a unique object for the foreign key. This ends up biting me because it introduces inconsistency, here is an example: >>> def print_elo(match_list): ... for match in match_list: ... print match.winner.id, match.winner.elo ... print match.loser.id, match.loser.elo ... >>> print_elo(teacher_match_list) 4 1192.0000000000 2 1192.0000000000 5 1208.0000000000 2 1192.0000000000 5 1208.0000000000 4 1192.0000000000 >>> teacher_match_list[0].winner.elo = 3000 >>> print_elo(teacher_match_list) 4 3000 # Object 4 2 1192.0000000000 5 1208.0000000000 2 1192.0000000000 5 1208.0000000000 4 1192.0000000000 # Object 4 >>> I solved this problem like so: def unify_refrences(match_list): """Makes each unique refrence to a model instance non-unique. In cases where multiple model instances are being used django creates a new object for each model instance, even if it that means creating the same instance twice. If one of these objects has its state changed any other object refrencing the same model instance will not be updated. This method ensure that state changes are seen. It makes sure that variables which hold objects pointing to the same model all hold the same object. Visually this means that a list of [var1, var2] whose internals look like so: var1 --> object1 --> model1 var2 --> object2 --> model1 Will result in the internals being changed so that: var1 --> object1 --> model1 var2 ------^ """ match_dict = {} for match in match_list: try: match.winner = match_dict[match.winner.id] except KeyError: match_dict[match.winner.id] = match.winner try: match.loser = match_dict[match.loser.id] except KeyError: match_dict[match.loser.id] = match.loser My question: Is there a way to solve the problem more elegantly through the use of QuerySets without needing to call save at any point? If not, I'd like to make the solution more generic: how can you get a list of the foreign keys on a model instance or do you have a better generic solution to my problem? Please correct me if you think I don't understand why this is happening.

    Read the article

  • Django - Better evaluation of relationship at the model level

    - by Brant
    Here's a simple relational pair of models. class Shelf(models.Model): name = models.CharField(max_length=100) def has_books(self): if Book.objects.filter(shelf=self): return True else: return False class Book(models.Model): shelf = models.ForeignKey(Shelf) name = models.CharField(max_length=100) Is there a better (or alternative) way to write the "has_book" method? I'm not a fan of the double database hit but I want to do this at the model level.

    Read the article

  • django sync db question

    - by Hulk
    In django models say this model exist in details/models.py class OccDetails(models.Model): title = models.CharField(max_length = 255) occ = models.ForeignKey(Occ) So when sync db is made the following fields get created and later to this of two more fields are added and sync db is made the new fields doesnt get created.How is this to be solved,Also what is auto_now=true in the below these are the new fields created_date = models.DateTimeField(auto_now_add=True) modified_date = models.DateTimeField(auto_now_add=True, auto_now=True)

    Read the article

  • derby + hibernate ConstraintViolationException using manytomany relationships

    - by user364470
    Hi, I'm new to Hibernate+Derby... I've seen this issue mentioned throughout the google, but have not seen a proper resolution. This following code works fine with mysql, but when I try this on derby i get exceptions: ( each Tag has two sets of files and vise-versa - manytomany) Tags.java @Entity @Table(name="TAGS") public class Tags implements Serializable { @Id @GeneratedValue(strategy=GenerationType.AUTO) public long getId() { return id; } @ManyToMany(targetEntity=Files.class ) @ForeignKey(name="USER_TAGS_FILES",inverseName="USER_FILES_TAGS") @JoinTable(name="USERTAGS_FILES", joinColumns=@JoinColumn(name="TAGS_ID"), inverseJoinColumns=@JoinColumn(name="FILES_ID")) public Set<data.Files> getUserFiles() { return userFiles; } @ManyToMany(mappedBy="autoTags", targetEntity=data.Files.class) public Set<data.Files> getAutoFiles() { return autoFiles; } Files.java @Entity @Table(name="FILES") public class Files implements Serializable { @Id @GeneratedValue(strategy=GenerationType.AUTO) public long getId() { return id; } @ManyToMany(mappedBy="userFiles", targetEntity=data.Tags.class) public Set getUserTags() { return userTags; } @ManyToMany(targetEntity=Tags.class ) @ForeignKey(name="AUTO_FILES_TAGS",inverseName="AUTO_TAGS_FILES") @JoinTable(name="AUTOTAGS_FILES", joinColumns=@JoinColumn(name="FILES_ID"), inverseJoinColumns=@JoinColumn(name="TAGS_ID")) public Set getAutoTags() { return autoTags; } I add some data to the DB, but when running over Derby these exception turn up (the don't using mysql) Exceptions SEVERE: DELETE on table 'FILES' caused a violation of foreign key constraint 'USER_FILES_TAGS' for key (3). The statement has been rolled back. Jun 10, 2010 9:49:52 AM org.hibernate.event.def.AbstractFlushingEventListener performExecutions SEVERE: Could not synchronize database state with session org.hibernate.exception.ConstraintViolationException: could not delete: [data.Files#3] at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:96) at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66) at org.hibernate.persister.entity.AbstractEntityPersister.delete(AbstractEntityPersister.java:2712) at org.hibernate.persister.entity.AbstractEntityPersister.delete(AbstractEntityPersister.java:2895) at org.hibernate.action.EntityDeleteAction.execute(EntityDeleteAction.java:97) at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:268) at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:260) at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:184) at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321) at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:51) at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1206) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:613) at org.hibernate.context.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:344) at $Proxy13.flush(Unknown Source) at data.HibernateORM.removeFile(HibernateORM.java:285) at data.DataImp.removeFile(DataImp.java:195) at booting.DemoBootForTestUntilTestClassesExist.main(DemoBootForTestUntilTestClassesExist.java:62) I have never used derby before so maybe there is something crutal that i'm missing 1) what am I doing wrong? 2) is there any way of cascading properly when I have 2 many-to-many relationships between two classes? Thanks!

    Read the article

  • How Can I Populate Default Form Data with a ManyToMany Field?

    - by b14ck
    Ok, I've been crawling google and Django documentation for over 2 hours now (as well as the IRC channel on freenode), and haven't been able to figure this one out. Basically, I have a model called Room, which is displayed below: class Room(models.Model): """ A `Partyline` room. Rooms on the `Partyline`s are like mini-chatrooms. Each room has a variable amount of `Caller`s, and usually a moderator of some sort. Each `Partyline` has many rooms, and it is common for `Caller`s to join multiple rooms over the duration of their call. """ LIVE = 0 PRIVATE = 1 ONE_ON_ONE = 2 UNCENSORED = 3 BULLETIN_BOARD = 4 CHILL = 5 PHONE_BOOTH = 6 TYPE_CHOICES = ( ('LR', 'Live Room'), ('PR', 'Private Room'), ('UR', 'Uncensored Room'), ) type = models.CharField('Room Type', max_length=2, choices=TYPE_CHOICES) number = models.IntegerField('Room Number') partyline = models.ForeignKey(Partyline) owner = models.ForeignKey(User, blank=True, null=True) bans = models.ManyToManyField(Caller, blank=True, null=True) def __unicode__(self): return "%s - %s %d" % (self.partyline.name, self.type, self.number) I've also got a forms.py which has the following ModelForm to represent my Room model: from django.forms import ModelForm from partyline_portal.rooms.models import Room class RoomForm(ModelForm): class Meta: model = Room I'm creating a view which allows administrators to edit a given Room object. Here's my view (so far): def edit_room(request, id=None): """ Edit various attributes of a specific `Room`. Room owners do not have access to this page. They cannot edit the attributes of the `Room`(s) that they control. """ room = get_object_or_404(Room, id=id) if not room.is_owner(request.user): return HttpResponseForbidden('Forbidden.') if is_user_type(request.user, ['admin']): form_type = RoomForm elif is_user_type(request.user, ['lm']): form_type = LineManagerEditRoomForm elif is_user_type(request.user, ['lo']): form_type = LineOwnerEditRoomForm if request.method == 'POST': form = form_type(request.POST, instance=room) if form.is_valid(): if 'owner' in form.cleaned_data: room.owner = form.cleaned_data['owner'] room.save() else: defaults = {'type': room.type, 'number': room.number, 'partyline': room.partyline.id} if room.owner: defaults['owner'] = room.owner.id if room.bans: defaults['bans'] = room.bans.all() ### this does not work properly! form = form_type(defaults, instance=room) variables = RequestContext(request, {'form': form, 'room': room}) return render_to_response('portal/rooms/edit.html', variables) Now, this view works fine when I view the page. It shows all of the form attributes, and all of the default values are filled in (when users do a GET)... EXCEPT for the default values for the ManyToMany field 'bans'. Basically, if an admins clicks on a Room object to edit, the page they go to will show all of the Rooms default values except for the 'bans'. No matter what I do, I can't find a way to get Django to display the currently 'banned users' for the Room object. Here is the line of code that needs to be changed (from the view): defaults = {'type': room.type, 'number': room.number, 'partyline': room.partyline.id} if room.owner: defaults['owner'] = room.owner.id if room.bans: defaults['bans'] = room.bans.all() ### this does not work properly! There must be some other syntax I have to use to specify the default value for the 'bans' field. I've really been pulling my hair out on this one, and would definitely appreciate some help. Thanks!

    Read the article

  • get average from set of objects in django

    - by dotty
    Hay, i have a simple rating system for a property. You give it a mark out of 5 (stars). The models are defined like this def Property(models.Model) # stuff here def Rating(models.Model) property = models.ForeignKey(Property) stars = models.IntegerField() What i want to do is get a property, find all the Rating objects, collect them, then get the average 'stars' from them. any ideas how to do this?

    Read the article

  • How do I use Django to insert a Geometry Field into the database?

    - by alex
    class LocationLog(models.Model): user = models.ForeignKey(User) utm = models.GeometryField(spatial_index=True) This is my database model. I would like to insert a row. I want to insert a circle at point -55, 333. With a radius of 10. How can I put this circle into the geometry field? Of course, then I would want to check which circles overlap a given circle. (my select statement)

    Read the article

  • Django query get recent record for each entry and display as combined list

    - by gtujan
    I have two models device and log setup as such: class device(models.Model): name = models.CharField(max_length=20) code = models.CharField(max_length=10) description = models.TextField() class log(model.Model): device = models.ForeignKey(device) date = models.DateField() time = models.TimeField() data = models.CharField(max_length=50) how do I get a list which contains only the most recent record/log (based on time and date) for each device and combine them in the format below: name,code,date,time,data being a Django newbie I would like to implement this using Django's ORM. TIA!

    Read the article

  • 2 fields unique

    - by xRobot
    I have this model: class blog(models.Model): user = models.ForeignKey(User) mail = models.EmailField(max_length=60, null=False, blank=False) name = models.CharField(max_length=60, blank=True, null=True) I want that (user,email) are unique togheter. For example: This is allowed: 1, [email protected], myblog 2, [email protected], secondblog This is NOT allowed: 1, [email protected], myblog 1, [email protected], secondblog Is this possible in Django ?

    Read the article

  • Django multiple many to many fields?

    - by Tom
    Hello everybody I am building a news app for my website. I want to use a sort of tag system. Each news article can have different and multiple tags. All tags are saved in a tag model, and i want to connect the tags to the newsarticle. Now is this possible with: tags = models.ForeignKey( TagsModel ) for one tag, but how i can do this with multiple of them? Thank you!

    Read the article

  • Creating form object for variable kind of form.

    - by Bunny Rabbit
    i want to create a form for users to submit questions in django ..so far the models i have created are class Question(models.Model): statement=models.CharField(max_length=100) class Choice(models.Model): statement=models.CharField(max_length=100) value=models.IntegerField() question=models.ForeignKey(Question) Now i want to write a Form class for creating a above form but the problem is the number of choices are variable,a user can decide how many choices a question must have .How do i do that in django?

    Read the article

  • Oracle: What does `(+)` do in a WHERE clause?

    - by Jonathan Lonowski
    Found the following in an Oracle-based application that we're migrating (generalized): SELECT Table1.Category1, Table1.Category2, count(*) as Total, count(Tab2.Stat) AS Stat FROM Table1, Table2 WHERE (Table1.PrimaryKey = Table2.ForeignKey(+)) GROUP BY Table1.Category1, Table1.Category2 What does (+) do in a WHERE clause? I've never seen it used like that before.

    Read the article

  • Combine Related Resources With TastyPie

    - by Aaron Ng
    How can I combine multiple Resources in TastyPie? I have 3 models I'd like to combine: users, profiles and posts. Ideally I'd like profiles nested within user. I'm not sure where to go from here. class UserResource(ModelResource): class Meta: queryset = User.objects.all() resource_name = 'user' fields = ['username','id','date_joined'] #Improper Auth authorization = Authorization() class UserProfileResource(ModelResource): class Meta: queryset = UserProfile.objects.all() resource_name = 'profile' class UserPostResource(ModelResource): user = fields.ForeignKey(UserResource,'user', full=True) class Meta: queryset = UserPost.objects.all() resource_name = 'userpost' #Improper Auth authorization = Authorization()

    Read the article

  • Does CakePHP treat all INT fields as ID's for join tables?

    - by Jonnie
    I am trying to save a User, their Profile, and some tags and my join table that links the profile and the tags keeps getting messed up. The profile model is called Instructor, the tag model is called Subject. The Instructor has a phone number and a zip code and for some reason CakePHP thinks these are the fields it should use when creating entries in my join table. My Join table always comes out as: id | instructor_id | subject_id | 1 | 90210 | 1 | // thinks that the zip code is an instructor_id 2 | 1112223333 | 1 | // thinks that the phone number is an instructor_id 3 | 1 | 1 | // thinks that user_id is an instructor_id 4 | 1 | 1 | // the actual instructor_id, this one's correct 5 | 90210 | 2 | 6 | 1112223333 | 2 | 3 | 1 | 2 | 4 | 1 | 2 | My Models: class Instructor extends AppModel { var $name = 'Instructor'; var $belongsTo = array('User', 'State'); var $hasAndBelongsToMany = array( 'Subject' = array( 'className' = 'Subject', 'joinTable' = 'instructors_subjects', 'foreignKey' = 'instructor_id', 'associationForeignKey' = 'subject_id', 'unique' = true, 'conditions' = '', 'fields' = '', 'order' = '', 'limit' = '', 'offset' = '', 'finderQuery' = '', 'deleteQuery' = '', 'insertQuery' = '' ) ); } class Subject extends AppModel { var $name = 'Subject'; var $hasAndBelongsToMany = array( 'Instructor' = array( 'className' = 'Instructor', 'joinTable' = 'instructors_subjects', 'foreignKey' = 'subject_id', 'associationForeignKey' = 'instructor_id', 'unique' = true, 'conditions' = '', 'fields' = '', 'order' = '', 'limit' = '', 'offset' = '', 'finderQuery' = '', 'deleteQuery' = '', 'insertQuery' = '' ) ); } My Model Associations: User hasOne Instructor Instructor belongsTo User Instructor hasAndBelongsToMany Subject Subject hasAndBelongsToMany Instructor My form data looks like: Array ( [User] = Array ( [username] = MrInstructor [password] = cddb06c93c72f34eb9408610529a34645c29c55d [group_id] = 2 ) [Instructor] = Array ( [name] = Jimmy Bob [email] = [email protected] [phone] = 1112223333 [city] = Beverly Hills [zip_code] = 90210 [states] = 5 [website] = www.jimmybobbaseballschool.com [description] = Jimmy Bob is an instructor. [user_id] = 1 [id] = 1 ) [Subject] = Array ( [name] = hitting, pitching ) ) My function for processing the form looks like: function instructor_register() { $this-set('groups', $this-User-Group-find('list')); $this-set('states', $this-User-Instructor-State-find('list')); if (!empty($this-data)) { // Set the group to Instructor $this-data['User']['group_id'] = 2; // Save the user data $user = $this-User-save($this-data, true, array( 'username', 'password', 'group_id' )); // If the user was saved, save the instructor's info if (!empty($user)) { $this-data['Instructor']['user_id'] = $this-User-id; $instructor = $this-User-Instructor-save($this-data, true, array( 'user_id', 'name', 'email', 'phone', 'city', 'zip_code', 'state_id', 'website', 'description' )); // If the instructor was saved, save the rest if(!empty($instructor)) { $instructorId = $this-User-Instructor-id; $this-data['Instructor']['id'] = $instructorId; // Save each subject seperately $subjects = explode(",", $this-data['Subject']['name']); foreach ($subjects as $_subject) { // Get the correct subject format $_subject = strtolower(trim($_subject)); $this-User-Instructor-Subject-create($this-data); $this-User-Instructor-Subject-set(array( 'name' = $_subject )); $this-User-Instructor-Subject-save(); echo ''; print_r($this-data); echo ''; } } } } }

    Read the article

  • Django model help

    - by dotty
    Does anyone have any clue why this doesn't work as expected. If i use the python shell and do team.game_set or team.games It returns an error AttributeError: 'Team' object has no attribute 'game' If i create a Game object and call game.home_team it returns the correct team object Heres my model class Team(models.Model): name = models.CharField(blank=True, max_length=100) class Game(models.Model): home_team = models.ForeignKey(Team, related_name="home_team")

    Read the article

  • How to get all objects with their children using django orm?

    - by kender
    Hi, I got very simple hierarchical structure: every object can have 0 or 1 parent. There's no limit on how many children each object can have. So in my application I got such a model: class O(Model): name = CharField(max_length = 20) parent = ForeignKey('O', related_name = 'children') Now I would like to be able to fetch all objects who have a particular one Object1 in their parent-tree (as in their parent or parent of their parents, etc). Should I use mptt or is there a simpler approach?

    Read the article

  • Getting field of type bytea in helper table when using GenerationType.IDENTITY

    - by dtrunk
    I'm creating my db scheme using Hibernate. There's a Table called "tbl_articles" and another one called "tbl_categories". To have a n-n relationship a helper table ("tbl_articles_categories") is needed. Here are all necessary Entities: @Entity @Table( name = "tbl_articles" ) public class Article implements Serializable { private static final long serialVersionUID = 1L; @Id @Column( nullable = false ) @GeneratedValue( strategy = GenerationType.IDENTITY ) private Integer id; // other fields... public Integer getId() { return id; } public void setId( Integer id ) { this.id = id; } // other fields... } @Entity @Table( name = "tbl_categories" ) public class Category implements Serializable { private static final long serialVersionUID = 1L; @Id @Column( nullable = false ) @GeneratedValue( strategy = GenerationType.IDENTITY ) private Integer id; // other fields public Integer getId() { return id; } public void setId( Integer id ) { this.id = id; } // other fields... } @Entity @Table( name = "tbl_articles_categories" ) @AssociationOverrides({ @AssociationOverride( name = "pk.article", joinColumns = @JoinColumn( name = "article_id" ) ), @AssociationOverride( name = "pk.category", joinColumns = @JoinColumn( name = "category_id" ) ) }) public class ArticleCategory { private ArticleCategoryPK pk = new ArticleCategoryPK(); public void setPk( ArticleCategoryPK pk ) { this.pk = pk; } @EmbeddedId public ArticleCategoryPK getPk() { return pk; } @Transient public Article getArticle() { return pk.getArticle(); } public void setArticle( Article article ) { pk.setArticle( article ); } @Transient public Category getCategory() { return pk.getCategory(); } public void setCategory( Category category ) { pk.setCategory( category ); } } @Embeddable public class ArticleCategoryPK implements Serializable { private static final long serialVersionUID = 1L; @ManyToOne @ForeignKey( name = "tbl_articles_categories_fkey_article_id" ) private Article article; @ManyToOne @ForeignKey( name = "tbl_articles_categories_fkey_category_id" ) private Category category; public ArticleCategoryPK( Article article, Category category ) { setArticle( article ); setCategory( category ); } public ArticleCategoryPK() { } public Article getArticle() { return article; } public void setArticle( Article article ) { this.article = article; } public Category getCategory() { return category; } public void setCategory( Category category ) { this.category = category; } } Now, I'm getting a serial type what I wanted in my articles table as well as in my categories table. But looking into my helper table, there aren't the expected fields article_id and category_id each of type integer - instead there are article and category of type bytea. What's wrong here? EDIT: Sorry, forgot to mention that I'm using PostgreSQL.

    Read the article

  • Inbreeding-immune database structure

    - by Nick Savage
    I have an application that requires a "simple" family tree. I would like to be able to perform queries that will give me data for an entire family given one id from a member in the family. I say simple because it does not need to take into account adoption or any other obscurities. The requirements for the application are as follows: Any two people will not be able to breed if they're from the same genetic line Needs to allow for the addition of new family lines (new people with no previous family) Need to be able to pull siblings, parents separately through queries I'm having trouble coming up with the proper structure for the database. So far I've come up with two solutions but they're not very reliable and will probably get out of hand quite quickly. Solution 1 involves placing a family_ids field on the people table and storing a list of unique family ids. Each time two people breed the lists are checked against each other to make sure no ids match and if everything checks out will merge the two lists and set that as the child's family_ids field. Example: Father (family_ids: (null)) breeds with Mother (family_ids: (213, 519)) -> Child (family_ids: (213, 519)) breeds with Random Person (family_ids: (813, 712, 122, 767)) -> Grandchild (family_ids: (213, 519, 813, 712, 122, 767)) And so on and so forth... The problem I see with this is the lists becoming unreasonably large as time goes on. Solution 2 uses cakephp's associations to declare: public $belongsTo = array( 'Father' => array( 'className' => 'User', 'foreignKey' => 'father_id' ), 'Mother' => array( 'className' => 'User', 'foreignKey' => 'mother_id' ) ); Now setting recursive to 2 will fetch the results of the mother and father, along with their mother and father, and so on and so forth all the way down the line. The problem with this route is that the data is in nested arrays and I'm unsure of how to efficiently work through the code. If anyone would be able to steer me in the direction of the most efficient way to handle what I want to achieve that would be tremendously helpful. Any and all help is greatly appreciated and I'll gladly answer any questions anyone has. Thanks a lot.

    Read the article

  • Django: select_related and GenericRelation

    - by Parand
    Does select_related work for GenericRelation relations, or is there a reasonable alternative? At the moment Django's doing individual sql calls for each item in my queryset, and I'd like to avoid that using something like select_related. class Claim(models.Model): proof = generic.GenericRelation(Proof) class Proof(models.Model): content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey('content_type', 'object_id') I'm selecting a bunch of Claims, and I'd like the related Proofs to be pulled in instead of queried individually.

    Read the article

  • In django, how can I include some default records in my models.py?

    - by kdt
    If I have a models.py like class WidgetType(models.Model): name = models.CharField(max_length=200) class Widget(models.Model): typeid = models.ForeignKey(WidgetType) data = models.CharField(max_length=200) How can I build in a set of built in constant values for WidgetType when I know I'm only going to have a certain few types of widget? Clearly I could fire up my admin interface and add them by hand, but I'd like to simplify configuration by having it built into the python.

    Read the article

< Previous Page | 6 7 8 9 10 11 12 13 14 15 16 17  | Next Page >