set minimum primary key for saving django models in database - django

I am new to Django.I have two models, Model A and a new Model B
class A:
firstname=models.CharField(max_length=20,blank=True,null=True)
email = models.EmailField(max_length=30,blank=True,null=True)
I have to migrate all the data from A to B in such that a way that primary key of a entry in Model A will be same in Model B. i.e
b.id = a.id where a and b are instance of A and B respectively.
but after this when i save a new instance the id generated is 5L, 6L etc. instead of incrementing the prmiary key of the last object created. Is there any way to fix this ??
I am using django 1.3 with postgresql 9.2.

You can copy data from table A into B using insert command
for example :
INSERT INTO A (id, firstname, email) SELECT b.id, b.firstname, b.email FROM B b;
Hope this will help you.

Related

Django annotate multiple objects based on multiple fields on a M2M relationship

I want to efficiently annotate Model A objects based on some fields on model B which has a plain many-to-many relationship (not using a through model) to A. A wrinkle is that I must find the oldest B for each A (using B.created_timestamp) but then populate using B.name. I want to use the ORM not raw SQL.
I tried this but it's not correct:
a_qs = A.objects.filter(id__in=ids)
ordered_qs = a_qs.order_by('-b__created_timestamp')
oldest_qs = Subquery(ordered_qs.values('b__name')[:1])
result = list(a_qs.annotate(name=oldest_qs))
This annotates every A with the same oldest name of B across all Bs related to A, but I want the oldest B among associated Bs for each A.
You forgot to set OuterRef https://docs.djangoproject.com/en/2.2/ref/models/expressions/
b_qs = B.objects.filter(a=OuterRef('pk')).order_by('-created_timestamp')
a_qs = A.objects.filter(id__in=ids).annotate(oldest_name=Subquery(b_qs.values('name')[:1])
result = list(a_qs)

Django select inherited model in a single query

Let's Assume I have a parent and a child tables which are implemented via inheritance in django.
models.py
class A(models.Model)
a = CharField()
class B(A):
b = CharField()
Now I want to select column b from table B I execute:
B.objects.only('b').get(id=4)
But this statement queries database 2 times:
SELECT `b`.`a_ptr_id`, `b`.`b` FROM `b` WHERE `b`.`a_ptr_id` = 4; args=(4,)
SELECT `a`.`a`, `b`.`a_id` FROM `b` INNER JOIN `a` ON (`b`.`a_ptr_id` = `b`.`id`) WHERE `b`.`a_ptr_id` = 4; args=(4,)
How do I generate SINGLE query like select b from b where a_ptr_id = ? using django models?
I want to query database one single time!
It turns out that only 1 query was generated. The 2nd query was caused because I checked all of this in debug mode. My IDE evaluated the object automatically which led to querying the database with
SELECT `a`.`a`, `b`.`a_id` FROM `b` INNER JOIN `a` ON (`b`.`a_ptr_id` = `b`.`id`) WHERE `b`.`a_ptr_id` = 4;

Laravel 5 checkout form insert foreign key into transaction table

Right now i'm study a flow of ecommerce site using laravel 5.0 and crinsane laravel package .
I have setup 2 tables
Which is transactions and orders table
The relations is orders has many transactions (1 transaction 1 type of item ) , and transactions belong to orders .
So , in transactions there is foreign key order_id which references to order tables id .
In routes I set route::post('checkout','OrderController#checkoutpost');
public function checkoutpost()
{
// Get input from checkout forms
$input = Request::all();
// Insert forms data into Order table
Order::create($input);
// Retrieve the session data and inserting into Transaction table
$formid = str_random();
$cart_content = Cart::content();
foreach ($cart_content as $cart) {
$transaction = new Transaction();
$products = Product::find($cart->id);
$transaction->product_id = $cart->id;
$transaction->form_id = $formid;
$transaction->qty = $cart->qty;
$transaction->total_price = $cart->price * $cart->qty;
// Here is the problem , how to assign this transaction>order_id into our "id" that just inserted earlier ..
$transaction->order_id = $orders;
$transaction->save();
Cart::destroy();
return redirect('product/checkout');
}
}
The problem is how to assign order_id with the id of data that we just insert earlier?
Any feedback were really appreciated, thank you
Firstly, when creating the Order you need to assign the return value:
// An instance of Order is returned, so the id is accessible.
$order = Order::create($input);
Then you can use:
// Remember to make 'id' a fillable field on the Order model if you want to do it this way.
$transaction->order_id = $order->id;
Have you try this AvoRed an Laravel E commerce its almost fully featured e commerce for Laravel if you like it give it a try and let me know the feedback if you have any.
AvoRed An Laravel E commerce

Open JPA how do I get back results from foreign key relations

Good morning. I have been looking all over trying to answer this question.
If you have a table that has foreign keys to another table, and you want results from both tables, using basic sql you would do an inner join on the foreign key and you would get all the resulting information that you requested. When you generate your JPA entities on your foreign keys you get a #oneToone annotation, #oneToMany, #ManyToMany, #ManyToOne, etc over your foreign key columns. I have #oneToMany over the foreign keys and a corresponding #ManyToOne over the primary key in the related table column I also have a #joinedON annotation over the correct column... I also have a basic named query that will select everything from the first table. Will I need to do a join to get the information from both tables like I would need to do in basic sql? Or will the fact that I have those annotations pull those records back for me? To be clear if I have table A which is related to Table B based on a foreign key relationship and I want the records from both tables I would join table A to B based on the foreign key or
Select * From A inner Join B on A.column2 = B.column1
Or other some-such non-sense (Pardon my sql if it is not exactly correct, but you get the idea)...
That query would have selected all column froms A and B where those two selected column...
Here is my named query that I am using....
#NamedQuery(name="getQuickLaunch", query = "SELECT q FROM QuickLaunch q")
This is how I am calling that in my stateless session bean...
try
{
System.out.println("testing 1..2..3");
listQL = emf.createNamedQuery("getQuickLaunch").getResultList();
System.out.println("What is the size of this list: number "+listQL.size());
qLaunchArr = listQL.toArray(new QuickLaunch[listQL.size()]);
}
Now that call returns all the columns of table A, but it lack's the column's of table B. My first instinct would be to change the query to join the two tables... But that kind of makes me think what is the point of using JPA then if I am just writing the same queries that I would be writing anyway, just in a different place. Plus, I don't want to overlook something simple. So what say you stack overflow enthusiasts? How does one get back all the data of joined query using JPA?
Suppose you have a Person entity with a OneToMany association to the Contact entity.
When you get a Person from the entityManager, calling any method on its collection of contacts will lazily load the list of contacts of that person:
person.getContacts().size();
// triggers a query select * from contact c where c.personId = ?
If you want to use a single query to load a person and all its contacts, you need a fetch in the SQL query:
select p from Person p
left join fetch p.contacts
where ...
You can also mark the association itself as eager-loaded, using #OneToMany(lazy = false), but then every time a person is loaded (vie em.find() or any query), its contacts will also be loaded.

Django AutoField not returning new primary_key

We've got a small problem with a Django project we're working on and our postgresql database.
The project we're working on is a site/db conversion from a PHP site to a django site. So we used inspect db to generate the models from the current PHP backend.
It gave us this and we added the primary_key and unique equals True:
class Company(models.Model):
companyid = models.IntegerField(primary_key=True,unique=True)
...
...
That didn't seem to be working when we finally got to saving a new Company entry. It would return a not-null constraint error, so we migrated to an AutoField like below:
class Company(models.Model):
companyid = models.AutoField(primary_key=True)
...
...
This saves the Company entry fine but the problem is when we do
result = form.save()
We can't do
result.pk or result.companyid
to get the newly given Primary Key in the database (yet we can see that it has been given a proper companyid in the database.
We are at a loss for what is happening. Any ideas or answers would be greatly appreciated, thanks!
I just ran into the same thing, but during a django upgrade of a project with a lot of history. What a pain...
Anyway, the problem seems to result from the way django's postgresql backend gets the primary key for a newly created object: it uses pg_get_serial_sequence to resolve the sequence for a table's primary key. In my case, the id column wasn't created with a serial type, but rather with an integer, which means that my sequence isn't properly connected to the table.column.
The following is based on a table with the create statement, you'll have to adjust your table names, columns and sequence names according to your situation:
CREATE TABLE "mike_test" (
"id" integer NOT NULL PRIMARY KEY,
"somefield" varchar(30) NOT NULL UNIQUE
);
The solution if you're using postgresql 8.3 or later is pretty easy:
ALTER SEQUENCE mike_test_id_seq OWNED BY mike_test.id;
If you're using 8.1 though, things are a little muckier. I recreated my column with the following (simplest) case:
ALTER TABLE mike_test ADD COLUMN temp_id serial NOT NULL;
UPDATE mike_test SET temp_id = id;
ALTER TABLE mike_test DROP COLUMN id;
ALTER TABLE mike_test ADD COLUMN id serial NOT NULL PRIMARY KEY;
UPDATE mike_test SET id = temp_id;
ALTER TABLE mike_test DROP COLUMN temp_id;
SELECT setval('mike_test_id_seq', (SELECT MAX(id) FROM mike_test));
If your column is involved in any other constraints, you'll have even more fun with it.