Django - combining forms for related models - django-forms

Is there a common method/best practice/any means for combining forms that span multiple related models?
I want to create/edit model objects along with other, related model objects on the same page. Basically, being able to create/edit one model instance and another set of model instances related by a foreign key.
Not a great explanation, I know.
class Person(models.Model):
name = models.CharField(max_length=64, unique=True)
class PhoneNumber(models.Model):
person = models.ForeignKey(Person)
description = models.CharField(max_length=64, blank=True, null=True)
number = models.CharField(max_length=32, blank=True, null=True)
I want to be able to create/edit a person, along with all their associated phone numbers using a single form/page.
I've done this before using this nested form example, but it seems quite hackish.

Yes! Use formsets, specifically https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#inline-formsets

Related

Django: during model save, assigning the current user of an object to owner defined as m2m relationship

I'm a Django trainee and would kindly appreciate some help.
Assigning a user as owner for an object seems to be well documented. However,
I am trying to assign MORE than one user as the owner of an object and struggling with it.
Using the below code that I found as example in the documentation, seems to apply to a foreignkey definition of owner and does not work during save for owner defined with many to many relationship.
Providing a simplified version of my models.py as follows :
Class Article(models.Model):
...
owner = models.ManytoManyField(User, blank=True)
...
Using an example I found in the django documentation, I have coded in admin.py:
class ArticleAdmin(admin.ModelAdmin):
def save_model(self, request, obj, form, change):
obj.owner = request.user
super().save_model(request, obj, form, change)
Initially, I would like to assign as the owner, the current user who CREATES or ADDS the object ( with the intention of assigning other users later , hence the many to many definition for owner and not a foreign key definition).
What would the equivalent code be for my purpose? Thanks in advance.

How can transform field names to work with existing API calls in django-rest-framework?

I have a Django app that needs to allow an existing API to make calls to it.
The existing API makes calls like:
/api/product
which expects fields named:
product_id, heading, unit
but the Django app returns fields named:
product_id, title, unit
Is there a way I can keep both ends happy but transforming the names during serialization?
You could create a custom ModelSerializer creating a heading filed name, and setting the source.
class ProductSerializer(serializers.ModelSerializer):
heading = serializers.CharField(source='title')
class Meta(object):
model = Product
fields = (
'product_id',
'heading',
'unit')

Magento save many to many models

I have created a custom module with 3 models (student, room, studentroom).
The studentroom is used to store the relation between student & room (manytomany).
I have maked the form + grid to the students and rooms and i can create both of them. i want now to add a multiselect in the student form to select the rooms (until now its ok). When i save or edit my student how can i save or display also the association in studentroom.
Anyone has an idea ? A module with the same functionalities ?
Thx for advance
Magento's ORM has no built-in methods for the sort of one to many and many to many relationships you're describing above. As such, it's up to each individual developer to implement their own save methods that (before or after calling parent::save()) handle any extra relationships an object might have.

Is there a way to pre-lookup related field models?

I am exposing an API for a particular model, and want to serialize some of its related fields. These related fields are commonly repeated, and I don't want to have to do a numerous db queries for each related field serialization. Is there a simple way to pre-query all related instances, and then have have the RelatedField serializer look it up in a dictionary? Or maybe to specify from the ModelSerializer of the related field?
You can use Django's standard prefetch_related and select_related methods on your queryset.
On the view, use the queryset attribute, rather than the model shortcut.
For example...
class ExampleView(generics.ListCreateAPIView):
serializer_class = ExampleSerializer
queryset = Example.objects.select_related(...)

Hibernate: Child table having two different ManyToOne relationships

In the Spring/Hibernate/Java/Tomcat app I'm writing I have a OneToMany relationship between an Organization and its Contacts.
Organization 1:M Contact (has foreign key org_id)
In Organization I have this field:
#OneToMany(mappedBy="organization")
private List<Contact> contacts;
In Contact I have this field:
#ManyToOne
#JoinColumn(name="org_id")
private Organization organization;
All is working OK so far. Now I'm adding the concept of an Offer. The Offer can be made by an Organization, and you speak with the designated Contact for that particular Offer.
Offer has foreign keys for its organization (org_id) and designated contact (contact_id).
So far, the Offer would look like:
#OneToOne
#JoinColumn(...)
private Organization offering_org;
#OneToOne
#JoinColumn(...)
private Contact offering_contact;
Here comes the point of my question. I've already annotated the Contact class for use with Organization. If I try to persist the Offer object in the usual Hibernate way, I'll need to store copies of an Organization object and a Contact object into the Offer object. This seems to conflict with my existing Organization : Contact use of the two Java classes. For example, if I've a 1:1 with Offer, if I put this into the Contact class do I get an optional use of either or a mandatory simultaneous use of both?
Since the Offer is yet another relationship, do I need to write a data transfer object version of Contact for use in the Offer relationship?
Thanks,
Jerome.
Perhaps I do not fully understand the problem but I'd just do something like this:
// contact & organization being already persisted entity objects
Offer offer = new Offer();
offer.setOffering_org(organization);
offer.setOffering_contact(contact);
// Persisting the new Offer object to the database,
// implicitly making the relations.
service.saveObject(offer);
I see no reason to create copy(s) of the organization object?
It just happens to be that the collection of "contacts" in the Organization object can also be a Contact within one or more Offer objects.
I'm thinking that my original question is kind of stupid. What I did try is to put this in Offer.java:
#Column(name="org_id")
private Long orgId = null;
#Column(name="contact_id")
private Long contactId = null;
I fill orgId manually because an offer is always tied to the user's Organization. It is a hidden field in the web page.
I put a SELECT filled with appropriate Contact objects (contact.id, contact.name) in the web page.
When the web page is submitted the Offer's orgId and contactId fields are filled in the #ModelAttribute parameter. This takes me where I want to go.
To address the comments of Mr. mspringer, your example could work (you illustrated a "create new" situation) if I were willing to use an Organization or Contact list in my Offer object. It is also somewhat the topic of my original question. But since I see that I don't really want to play with the expanded objects within Offer, nor do I wish to, I can avoid the topic of my original question.
Thanks to all who looked at my exercise in confusion.

Resources